HMC Homepage      CS Home

How do I use LaTeX?

Introduction

LaTeX is a powerful typesetting and formating tool. It can produce just about any document format under the sun, but can be initially intimidating. In contrast to some other tools, LaTeX-formated documents aren't created in a fancy GUI that shows what the finished document will look like. Instead, documents are created in plain text files with commands embedded within the body of the text. This file is then processed by the LaTeX compiler to produce a typeset file.

Creating, viewing, and printing a document

  1. First, to create a tex file, type:

    > {emacs,vi} document.tex

  2. To compile the file, type:

    > latex document

  3. To view how the file will be printed, type:

    > xdvi document

  4. To print the file, type:

    > dvips document

  5. To create a PostScript file, type

    > dvips -o document.ps document

  6. To create a PostScript file which uses PostScript Type 1 fonts (highly recommended if you want to make a PDF file), type

    > dvips -Ppdf -o document.ps document

  7. To create a PDF file, type

    > ps2pdf document.ps document.pdf

  8. To create a HTML file, type

    > tth < document

  9. To create a gif image, first create a PostScript file, then type

    > pstogif document.ps

General Format of a .tex file

All programs should start with a declaration of the style of the document. For example:

> \documentclass[11pt]{article}

See Document Style for more details.

Declare the beginning of the text by placing

> \begin{document}

at the beginning of the text and end with

> \end{document}

Some things to be aware of when writing:

  1. The following 10 characters are interpreted as commands by LaTeX.

    & $ # % _ { } ^ ~ \

    Seven of these can be printed by typing a backslash in front of them.

    \& \$ \# \% \_ \{ \}

    \ can be printed by typing $\backslash$

    • The `braces' { and } are used for grouping. Control sequences included in such a group apply only to the contents of the group.
    • The character $ is used when embedding mathematical expressions in paragraphs of ordinary text in order to change into and out of `mathematics mode'.
    • The characters ^ and _ are used in mathematical expressions to produce superscripts and subscripts respectively.
    • The character # is used to specify arguments in definitions of control sequences. The special character & is used when typesetting tables in order to separate entries in different columns.
  2. Typing any number of white spaces will be treated as one space by the LaTeX compiler. A blank line will be interpreted as the end of a paragraph.

  3. Use % for comments

    The character % is used to introduce `comments' into the input file that do not appear in the final document: all characters occuring after % on any line of the input file are ignored by LaTeX.

Document Style

There are three comands used to specify the overall style of a LaTeX document.

  1. \documentclass[options]{class}

    A LaTeX document should begin with a \documentclass command and any text to be printed must be included between \begin{document} and \end{document} commands.

    The command begins with \documentclass and ends with the names of one of the available styles, enclosed in braces. The available styles are:

    Styles:

    article
    Use article style.
    report
    Use report style.
    book
    Use book style.
    letter.
    Use letter style.

    Between the ``\documentclass'' and the name of the document style, one may place a list of options. These options are separated by commas and the list of options is enclosed in square brackets (as in the above example). The options available include the following:

    Options:

    11pt
    Specifies a size of type known as eleven-point, which is ten percent larger than the ten-point type normally used.
    12pt
    Specifies a twelve-point type size, which is twenty percent larger than ten-point.
    twocolumn
    Produces two-column output.
    a4paper
    This ensures that the page is appropriately positioned on A4 size paper.

    Typing simply \documentclass{article} will produce a document in ten-point type size. However the printed output will not be nicely positioned on A4 paper, since the default size is intended for a different (American) paper size.

  2. \usepackage[options]{pkg}

    pkg: color graphics amstex latexsym label makeidx

    Long description of what \usepackage does goes here.

  3. \pagestyle{style}

    style: of head and foot: plain empty headings myheadings

    This command tells LaTeX what (if anything) to put in the page headings.

    Pages will be automatically numbered at the bottom of the page, unless you specify otherwise. This can be done using the \pagestyle command. This command should come after the \documentclass command and before the \begin{document} command. The avaliable options are:

    plain
    The page number is at the foot of the page. This is the default page style for the article and report document styles.
    empty
    No page number is printed.
    headings
    The page number (and any other information determined by the document style) is put at the top of the page.
    myheadings
    Similar to the headings pagestyle, except that the material to go at the top of the page is determined by \markboth and \markright commands (see the LaTeX manual).

    For example, the input file

    \documentclass[a4paper]{article}
    \pagestyle{empty}
    \begin{document}
    The main body of the document is placed here.
    \end{document}
    
    produces a document without page numbers, using the standard ten-point type size.

Here is a typical LaTeX input file:

\documentclass[a4paper,12pt]{article}
\begin{document}

This is the first paragraph of a typical document. It is
produced in a `12~point' size. A \emph{point} is a unit
of length used by printers. One point is approximately
$1/72$~inch. In a `12~point' font the height of the
parentheses is 12~points (i.e. about $1/6$~inch) and the
letter~`m' is about 12 points long. 

This is the second paragraph of the document. There are
also `10 point' and `11 point' styles available in LaTeX.
The required size is specified in the `documentstyle'
command. If no such size is specified then the 10~point
size is assumed.

\end{document}

Sectioning and Table of Contents

Section headings of various sizes are produced (in the article document style) using the commands below. LaTeX will number the sections and subsections automatically. The title of the section should be surrounded by braces and placed immediately after the relevant command. The sectioning commands for articles are:

  1. \section
  2. \subsection
  3. \subsubsection
  4. \paragraph
  5. \subparagraph
  6. \appendix

Additionally, to create an unnumbered section the

\part

command is avaliable.

The report and book document styles have all of these commands avaliable as well as a top level

\chapter

command.

To add a table of contents to a document using this method of sectioning, simply insert the

\tableofcontents

command into your input file. This command will expand into an automatically created table of contents.

Text Formatting

Text Style

Changing the style of a block of text is done by enclosing the text in curly braces and preceding it with the appropriate command.
\textup{...}
Place some text with an upright shape.
\emph{...}
Emphasise some text.
\textit{...}
Italizise some text.
\textbf{...}
Place some text in bold.
\textsf{...}
Place the text in sans serif font.
\textsc{...}
Place some text in all caps.
\texttt{...}
Place some text in a typewriter font.
\textrm{...}
Place some text in a Roman font.
\textsl{...}
Place some text in a slant font.

All of the commands that begin with \text should be changed to begin with \math when applying them to mathematical expressions.

Font sizes


Quotations

LaTeX differentiates between opening and closing quotation marks.

The symbol ` (upper left on most keyboards) is an opening quotation mark and ' (middle right on most keyboards) is the closing quotation mark. Double quotes are obtained by typing two adjacent single quotes.

LaTeX can also automatically indent and format your quotations.

Short, quotations can be added using the \begin{quote} ... \end{quote} command.

Longer block quotes can be added using \begin{quotation} ... \end{quotation}

Managing whitespace

LaTeX treats multiple whitespace characters in the source file as a single whitespace, but provides several commands to control how whitespace is distributed.

\ [A \ followed by a blank space]
This command inserts one blank space into the text.
\\
This command will end the current line and move to the next.
\\[length]
This is like the \\ command, but it leaves length space before the next line.
\par
This command begins a new paragraph.
\noindent
This command suppresses the indentation that is automatically done at the beginning of a paragraph.
\indent
This command inserts indentation equal to a new paragraph.
\begin{verbatim}...\end{verbatim}
All text between these commands will be typeset exactly as it is in the source file. All whitespace will be preserved. This is useful when typesetting code.
\linebreak
This command inserts a linebreak at this exact point in the text.
\linespread{1.3}
This command switches to 1.5 line spacing.
\pagebreak
This command inserts a page break at this exact page.
\newpage
This command tells LaTeX to begin a new page, while allowing it some latitude for formating.
\hspace{length}
This command inserts horizontal blank space of the given length. If a line break occurs during the blank space, the blank space will be skipped.
\hspace*{length}
This command is exactly like \hspace, but will always insert the blank space, regardless of whether there is a line break.
\vspace{length}
This command inserts vertical blank space of the given length.
\footnote{text}
This command inserts text as a footnote on the bottom of the page and references it..
The recognized units for lengths are given in the following table:
pt  point         (1 in = 72.27 pt)
pc  pica          (1 pc = 12 pt)
in  inch          (1 in = 25.4 mm)
bp  big point     (1 in = 72 bp)
cm  centimeter    (1 cm = 10 mm)
mm  millimeter
dd  didot point   (1157 dd = 1238 pt)
cc  cicero        (1 cc = 12 dd)
sp  scaled point  (65536 sp = 1 pt)

Dashes

LaTeX allows you to produce dashes of various length, known as `hyphens', `en-dashes' and `em-dashes'. Hyphens are obtained in LaTeX by typing -, en-dashes by typing -- and em-dashes by typing --- .

Accents

To typeset an accent, simply embed the appropriate symbol into the document.

Additional accents can be found at The Comprehensive LaTeX symbol list

Lists

LaTeX supports both numbered and itemized lists.

\begin{enumerate} ... \end{enumerate}
Wrap these commands around a numbered list.
\begin{itemize} ... \end{itemize}
Wrap these commands around an unnumbered list.
\item{label}
Precede each item in the list with this command to give it either a number or a tick mark depending on the list type. The label field is optional.
\begin{description} ... \end{description}
When using labeled items, wrapping the item description in these commands will indent them and format them nicely.

Mathematical Symbols

All mathematical symbols in LaTeX should be enclosed in $ ... $ .

Use $$ ... $$ to center mathematical expressions on a new line.

$\frac{numerator}{denominator}
Inserts a fraction
$^{exponent}
Makes the contents of the braces into an exponent. Multiple ^{...}'s can be nested to get multiple levels of exponentiation.
$_{subscript}
Makes the contents of the braces into a subscript. Multiple subscripts can also be nested.
\sqrt{...}
Places the contents inside a square root.
\sqrt[n]{...}
Places the contents inside a nth root
\partial
Inserts a partial derivative symbol.
\lim_{...}
Inserts a limit symbol. The contents of the braces are placed underneath the symbol.
\sum_{lower limit}^{upper limit}
Inserts a summation symbol.
\int_a^b
Inserts an integral from a to b
\overline{...}
Inserts a line over the expression.
\underline{...}
Inserts a line under the expression.
\overbrace{...}
Inserts a horizontal brace over the expression.
\underbrace{...}
Inserts a horizontal brace under the expression.
\overrightarrow{...}
Inserts a right arrow over the expression.
\overleftarrow{...}
Inserts a left arrow over the expression.

Examples:

The LaTeX code for these is

Greek Letters

Greek letters are produced in mathematics mode by preceding the name of the letter by a backslash \. Thus to obtain the formula one types A = \pi r^2.

Here are the control sequences for the standard forms of the lowercase Greek letters:

Note: Some Greek letters occur in variant forms. The variant forms are obtained by preceding the name of the Greek letter by `var'.

Upper case Greek letters are obtained by making the first character of the name upper case. Here are the control sequence for the uppercase letters:

Other Mathematical Symbols

More symbols can be found at AGU symbol list

Even more symbols can be found in the Comprehensive LaTeX symbol list.

The Comprehensive LaTeX symbol list

AMS Formated Proofs and Theorems

The American Mathematical Society publishes a set of LaTeX styles for articles submitted to their journals. The environments used for theorems and proofs are summarized here. More information can be found in the documentation of the amsthm package located here.

The first thing that any LaTeX document using AMSthm must do is place the command

\usepackage{amsthm}

at the beginning of the document to tell the LaTeX compiler to include AMSthm.

\begin{proof}[heading text] ... \end{proof}
The text enclosed will be formated as a proof. heading text will be used as the proof title; if no heading text is specified the phrase "Proof" will be used. A QED symbol is automatically appended at the end of the proof.
\begin{Theorem style name} ... \end{Theorem style name}
The enclosed text will be formated according to the theorem style specified.

To place a theorem using AMSthm, we need to first define the theorem environment.

This must be done after the \documentclass command, but before \begin{document}. AMSthm allows you to modify these environments, but provides three basic templates:

plain
The text enclosed will be formatted in an AMS style suitable for a theorem, lemma, corollary, proposition, conjecture, or algorithm.
definition
The text enclosed will be formatted as a definition, condition, problem or example.
remark
The text enclosed will be formatted as a remark, note, notation, claim, summary, acknowledgment, case or conclusion.

To use one of these or any other custom style, use the command

\theoremstyle{style}
Change the current style to style .

Once the style is set up how you want it, create the new theorem environment with the command:

\newtheorem{Theorem type}{Theorem title}
This command defines a new theorem environment named Theorem type. Each instance will have the title Theorem title

Modifying numbering

By default, new theorem environments will be numbered. To get unnumbered theorems, use \newtheorem*.

By default, each theorem environment has its own numbering. e.g Lemma 1, Lemma 2, Theorem 1, Lemma 3, etc. Two environments can be made to share the same numbering sequence like this: Lemma 1, Lemma 2, Theorem 3, Lemma 4, etc.

To do this, use

\newtheorem{Theorem type}[Shared Numbering]{Theorem title}
This command defines a new theorem environment that shares a numbering system with Shared Numbering..

Normally, theorem numbers are located on the right of the theorem title. To move them to the left, use

\swapnumbers
Place this command before \theoremstyle to move numbering to the left of the title.

Here is a sample .tex file illustrating the use of AMSthm.

amsthmsample.tex

Tables

Tables can be produced in LaTeX using the tabular environment.

The \begin{tabular} command must be followed by a string of characters enclosed within braces which specifies the format of the table. For example, the string {lll} is a format specification for a table with three columns of left-justified text. Within the body of the table the ampersand character & is used to separate columns of text within each row, and the double backslash \\ is used to separate the rows of the table.

For example this is a table with vertical and horizontal lines. The table

[GIF Image]
is coded in LaTeX as follows:
\begin{tabular}{|r|r|}
\hline
$n$&$n!$\\
\hline
1 & 1\\
2 & 2\\
3 & 6\\
4 & 24\\
5 & 120\\
6 & 720\\
7 & 5040\\
8 & 40320\\
9 & 362880\\
10 & 3628800\\
\hline
\end{tabular}
In this example the format specification {|r|r|} after \begin{tabular} specifies that the table should consist of two columns of right-justified text, with vertical lines to the left and to the right of the table, and between columns.

Within the body of the table, the command \hline produces a horizontal line; this command can only be placed between the format specification and the body of the table (to produce a line along the top of the table) or immediately after a row separator (to produce a horizontal line between rows or at the bottom of the table).

In a tabular environment, the format specification after \begin{tabular} should consist of one or more of the following, enclosed within braces { and }:

l specifies a column of left-justified text
c specifies a column of centred text
r specifies a column of right-justified text
p{width} specifies a left-justified column of the given width
| inserts a vertical line between columns
@{text} inserts the given text between columns

A string str of characters in the format specification can be repeated num times using the construction *{num}{str}. For example, a table with 15 columns of right-justified text enclosed within vertical lines can be produced using the format specification {|*{15}{r|}}.

If additional vertical space is required between rows of the table, then this can be produced by specifying the amount of space within square brackets after \\. For example, one would use \\[6pt] to separate two rows of the table by 6 points of blank space.

A horizontal line in a table from column i to column j inclusive can be produced using \cline{i-j}. For example \cline{3-5} produces a horizontal line spanning columns 3, 4 and 5 of some table.

A command of the form \multicolumn{num}{fmt}{text} can be used within the body of a table to produce an entry spanning several columns. Here num specifies the number of columns to be spanned, fmt specifies the format for the entry (e.g., l if the entry is to be left-justified entry, or c if the entry is to be centred), and text is the text of the entry.

Many of these features are used in typesetting the table

[GIF Image]
which is coded in LaTeX as follows:
\begin{tabular}{|l||l|l||l|l|}
\hline
 &\multicolumn{2}{l|}{Singular}&\multicolumn{2}{l|}{Plural}\\
\cline{2-5}
 & English&\textbf{Gaeilge}& English&\textbf{Gaeilge}\\
\hline\hline
1st Person& at me&\textbf{agam}& at us&\textbf{againn}\\
2nd Person& at you&\textbf{agat}& at you&\textbf{agaibh}\\
3rd Person& at him&\textbf{aige}& at them&\textbf{acu}\\
 & at her&\textbf{aici}& & \\
\hline
\end{tabular}

Matrices

Matrices and other arrays are produced in LaTeX using the \textbf{array} environment. For example, suppose that we wish to typeset the following passage:

[GIF Image]
This passage is produced by the following input:
The \emph{characteristic polynomial} $\chi(\lambda)$ of the
$3 \times 3$~matrix
\[ \left( \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \right)\] 
is given by the formula
\[ \chi(\lambda) = \left| \begin{array}{ccc}
\lambda - a & -b & -c \\
-d & \lambda - e & -f \\
-g & -h & \lambda - i \end{array} \right|.\] 
First of all, note the use of \left and \right to produce the large delimiters around the arrays. As we have already seen, if we use
\left) ... \right)
then the size of the parentheses is chosen to match the subformula that they enclose. Next note the use of the alignment tab character & to separate the entries of the matrix and the use of \\ to separate the rows of the matrix, exactly as in the construction of multiline formulae described above. We begin the array with \begin{array} and end it with \end{array}. The only thing left to explain, therefore, is the mysterious {ccc} which occurs immediately after \begin{array}. Now each of the c's in {ccc} represents a column of the matrix and indicates that the entries of the column should be centred. If the c were replaced by l then the corresponding column would be typeset with all the entries left-justified, and r would produce a column with all entries right-justified. Thus
\[ \begin{array}{lcr}
\mbox{First number} & x & 8 \\
\mbox{Second number} & y & 15 \\
\mbox{Sum} & x + y & 23 \\
\mbox{Difference} & x - y & -7 \\
\mbox{Product} & xy & 120 \end{array}\] 
produces
[GIF Image]

We can use the array environment to produce formulae such as

[GIF Image]
Note that both columns of this array are set flush left. Thus we use {ll} immediately after \begin{array}. The large brace is produced using \left\{. However this requires a corresponding \right delimiter to match it. We therefore use the \emph{null delimiter} \right. discussed earlier. This delimiter is invisible. We can therefore obtain the above formula by typing
\[ |x| = \left\{ \begin{array}{ll}
         x & \mbox{if $x \geq 0$};\\
        -x & \mbox{if $x < 0$}.\end{array} \right. \] 

Graphics

The basic command to include an image in a document is

\includegraphics[llx,lly][urx, ury] {filename}
llx is the lower left x coordinate, lly is the lower left y coordinate. urx and ury are the upper-right coordinates. The coordinates are optional and indicate which portion of the image is to be included in the document. Without the coordinates, the entire image will be included. The default units are bp (72 per inch) although others can be specified.

Once a graphic has been specified, it may be scaled, reflected, or rotated:

\scalebox{h_scale}[v_scale]{text}
If v_scale is omitted, then it is assumed to be the same as h_scale.
\resizebox{h_length}{v_length}{text}
If one of v_length or h_length is given as ! then the other will be used for both.
\reflectbox{text}
Reflects the image horizontally.
\rotatebox{angle}{text}
Rotate the box counter-clockwise by angle degrees.

For example:

\includegraphics{apparatus.pdf}
\scalebox{.5}
\rotatebox{45}
In this case, apparatus.pdf is a PDF file containing the image to be included in the file. A variety of different file formats can be used, although EPS and PDF are the most widely used. The image has been reduced to 50% of original size and rotated 45 degrees.

XYPic Diagrams

XYPic is a package that can produce nicely typset diagrams.

To tell the compiler that we want to use XYPic, place this line at the beginning of the document:

\usepackage[all]{xy}

XYPic is usually used to produce matrix-based diagrams.

Each element is identified by its position on a NxN grid. These elements can then be connected by arrows and labeled.

A XYPic matrix diagram is inserted by using the

\xymatrix{...}

command. Inside the ... , place each cell in the diagram.

Cells on the same row are divided by & and rows are divided by \\ . For example,

was typset with the code:

\documentclass{article}
\usepackage[all]{xy}
\begin{document}

\xymatrix{A & B \\ C & D}

\end{document}

Arrows

To connect two cells with a arrow, insert the control code
\ar[direction]

direction can be any combination of the letters u, d, l, r indicating how many steps the arrow should move in each direction.

Different arrow styles can be inserted as shown:

Arrows can be curved using \ar@/^/[dir], \ar@/_/[dir], \ar@/_amount of curve/[dir], or \ar@/^amount of curve/[dir

was coded by:


\xymatrix { A\ar@/^/[rr] & B & C\\
            D\ar@/_/[rr] & E & F}

Labels

To label an arrow, do either \ar[dir]_{label} or \ar[dir]^{label} depending on whether you want the label above or below.

To place a label inside an arrow, do \ar[dir]|{label}

Note that even invisible arrows can be labeled; this can be used to place labels outside of any specific matrix cell.

Labels can be positioned at either the tail or head of the arrow using \ar[dir]^<{label} and \ar[dir]^>{label} respectively. Increasing the number of <'s or >'s will move the label towards the center.

was coded by:


\xymatrix{ A\ar[r]^{above} & B & G\ar[r]^<{tail} & H\\
           C\ar[r]_{below} & D & I\ar[r]^>{head} & J\\
           E\ar[r]|{in} & Famp & J\ar[r]^>>>{shift} & K}

Further XYPic information

Further information on XYPic can be obtained from the XYPic documentation.

XYPic directory on the Comprehensive Tex Archive

Error messages

The most common error message by far is "missing $ inserted":

! Missing $ inserted.
< inserted text >
                $
l.6 If we want to show that \log
                                {n} = 42$ then blah blah blah...
Notice that the line that was quoted by the LaTeX compiler has been split. The location of the split is where it tried to insert the '$' character. In this case we probably wanted to put the '$' in front of the "\log" instead, but the split is usually a good indication of roughly where the problem is.

Two other common error messages are "Underfull hbox" and "Overfull hbox". These refer to how full the document is, horizontally. An underfull hbox means that there is not really enough text to flesh out the paragraph, so LaTeX is forced to space it out. An overfull hbox is a bit more rare and indicates that there was so much text on a line that the line went off the edge of the page. Typically this only happens when LaTeX's word wrapper has been turned off (for example, in verbatim mode), as otherwise the compiler would simply wrap the line.

Sample .tex Files

Further Resources

Books

The terminal room (Beckman 102) has several useful reference texts for more in-depth help with LaTeX. They're on the bookshelf under the whiteboard, under "Markup/Publishing". Please don't remove them from the terminal room.

latex-l mailing list

The HMC latex-l mailing list is a good place to ask any questions about latex.

The Comprehensive Tex Archive Network

Contains many, many tex packages and their documentation.

The Comprehensive Tex Archive Network

AGU Symbol list

A good place to start looking for the command for a symbol is the AGU Symbol list.

AGU Symbol List

The Comprehensive Symbol List

If you can't find a symbol anywhere else, chances are its LaTeX code is somewhere in here.

The Comprehensive LaTeX symbol List


Copyright (c) HMC Computer Science Department. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License.''

HMC Computer Science Department
Contact Information
Last Modified Tuesday, 07-Feb-2006 13:25:03 PST