LaTeX/Print version
From Wikibooks, the open-content textbooks collection
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".
Contents
- Chapters
- Document Structure
- Errors and Warnings
- Title Creation
- Bibliography Management
- Tables
- Formatting
- Page Layout
- Mathematics
- Theorems
- Labels and Cross-referencing
- Indexing
- Algorithms and pseudocode
- Letters
- Importing Graphics
- Creating Graphics
- Floats, Figures and Captions
- Presentations
- Hyperlinks
- Colors
- Packages
- Advanced Topics
- Fonts
- Customizing LaTeX
- Collaborative Writing of LaTeX Documents
- Tips and Tricks
- General Guidelines
- Export To Other Formats
- Internationalization
- Appendices
- Installation
- Useful Measurement Macros
- Useful Size Commands
- Sample LaTeX documents
- Command Glossary
- Links
- Authors
- GNU Free Documentation License
Introduction
What is TeX
TeX (pronounced "Tech", with "ch" like in the Scottish "Loch") is a low-level markup and programming language created by Donald Knuth to typeset documents attractively and consistently. It's a programming language, in the sense that it supports the if-else construct, you can make calculations with it (that are performed while compiling the document), etc., but you would find it very hard to make anything else but typesetting with it. The fine control TeX offers makes it very powerful, but also difficult and time-consuming to use. Knuth started writing the TeX typesetting engine in 1977 to explore the potential of the digital printing equipment that was beginning to infiltrate the publishing industry at that time, especially in the hope that he could reverse the trend of deteriorating typographical quality that he saw affecting his own books and articles. TeX as we use it today was released in 1982, with some slight enhancements added in 1989 to better support 8-bit characters and multiple languages. TeX is renowned for being extremely stable, for running on many different kinds of computers, and for being virtually bug free.
The version number of TeX is converging to π and is now at 3.1415926.
Its name originates from the Greek word "τεχνολογία" (technologìa), which translates as "technology" in English; its first syllable is "τεχ", similar to TeX in the Latin alphabet. According to a different approach the name originates from the Greek word "τέχνη" (techni), which translates as art in English. In the second case the first syllable is "τεχ" again.
What is LaTeX
LaTeX (pronounced either "Lah-tech" or "Lay-tech") is a macro package based on TeX created by Leslie Lamport. Its purpose is to simplify TeX typesetting, especially for documents containing mathematical formulae. It is currently maintained by the LaTeX3 project. Many later authors have contributed extensions, called packages or styles, to LaTeX. Some of these are bundled with most TeX/LaTeX software distributions; more can be found in the Comprehensive TeX Archive Network (CTAN).
Since LaTeX comprises a group of TeX commands, LaTeX document processing is essentially programming. You create a text file in LaTeX markup. The LaTeX macro reads this to produce the final document.
Clearly this has disadvantages in comparison with a WYSIWYG (What You See Is What You Get) program such as Openoffice.org Writer or Microsoft Word:
- You can't see the final result straight away.
- You need to know the necessary commands for LaTeX markup.
- It can sometimes be difficult to obtain a certain 'look'.
On the other hand, there are certain advantages to the markup language approach:
- The layout, fonts, tables and so on are consistent throughout.
- Mathematical formulae can be easily typeset.
- Indexes, footnotes and references are generated easily.
- You are forced to correctly structure your documents.
The LaTeX-like approach can be called WYSIWYM, i.e. What You See Is What You Mean: you can't see what the final version will look like while typing. Instead you see the logical structure of the document. LaTeX takes care of the formatting for you.
The LaTeX document is a plain text file containing the content of the document, with additional markup. When the source file is processed by the macro package, it can produce documents in several formats. LaTeX natively supports DVI and PDF, but by using other software you can easily create PostScript, PNG, JPG, etc.
Prerequisites
At a minimum, you'll need the following programs to edit LaTeX:
- An editor (You can use a basic text editor like notepad or Notepad++ [1], but a dedicated LaTeX editor will be more useful).
- On Windows, TeXnicCenter [2] is a popular free and open source LaTeX editor.
- On Unix-like (including Mac OS X) systems, Emacsen and gvim provide powerful TeX environments for the tech-savvy, while Texmaker [3] and Kile [4] provide more user-friendly development environments.
- On Mac OS X, TexShop [5] is a full featured editor. It is also available in the MacTeX bundle obtained at http://www.tug.org/mactex.
- The LaTeX binaries and style sheets - e.g. MiKTeX [6] for Windows, TeX-live for Unix/Linux [7] and for Mac OS X [8].
- A DVI viewer to view and print the final result. Usually, a DVI viewer is included in the editor or is available with the binary distribution.
A distribution of LaTeX, with many packages, add-ins, editors and viewers for Unix, Linux, Mac and Windows can be obtained from the TeX users group at http://www.tug.org/texlive/.
Applications within a distribution
Here are the main programs you expect to find in any (La)TeX distribution:
- tex: the simplest compiler, it gets a TeX file and creates a DVI
- pdftex: it gets a TeX file, but creates a PDF file
- latex: the most used one: it gets a LaTeX file and creates a DVI
- pdflatex: from a LaTeX creates a PDF
- dvips: converts the DVI file to PostScript
- dvipdf: converts the DVI file to PDF
- dvipdfm: improved version of the previous one
When LaTeX was created, the only format it could create was DVI; then the PDF support was added by pdflatex, even if several people still don't use it. As it is clear from this short list, PDF files can be created with both pdflatex and dvipdfm; anyway, the output of pdflatex is much better than the other. DVI is an old format, and it does not support hyperlinks for example, while PDF does, so passing through DVI you will bring all the bad points of that format to PDF. Moreover the general output will be better using only pdflatex.
Strictly speaking, you would write your document slightly differently depending on the compiler you are using (latex or pdflatex). But as we will see later, it is possible to add a sort of abstraction layer, to hide the details of which compiler you're using, and the compiler will handle the translation itself.
Note that, since LaTeX is just a collection of macros for TeX, if you compile a plain TeX document with a LaTeX compiler (such as pdflatex) it will work, while the opposite is not true: if you try to compile a LaTeX source with a TeX compiler you will get only a lot of errors.
The following diagram shows the relationships between the (La)TeX source code and all the formats you can create from it:
The boxed red text represents the file formats, the blue text on the arrows represents the commands you have to use, the small dark green text under the boxes represents the image formats that are supported. Any time you pass through an arrow you lose some information, which might decrease the quality of your document. Therefore, in order to achieve the highest quality in your output file, you should choose the shortest route to reach your target format. This is probably the most convenient way to obtain an output in your desired format anyway. Starting from a LaTeX source, the best way is to use only latex for a DVI output or pdflatex for a PDF output, converting to PostScript only when it is necessary to print the document.
Most of the programs should be already within your LaTeX distribution; the others come with Ghostscript, which is a free and multi-platform software as well.
Chapter Export To Other Formats says more about what you can get from LaTeX source.
Chapters
Absolute Beginners
This tutorial is aimed at getting familiar with the bare bones of LaTeX. First, ensure that you have LaTeX installed on your computer (see Installation for instructions of what you will need). We will begin with creating the actual source LaTeX file, and then take you through how to feed this through the LaTeX system to produce quality output, such as postscript or PDF.
The LaTeX source
The first thing you need to be aware of is that LaTeX uses a markup language in order to describe document structure and presentation. What LaTeX does is convert your source text, combined with the markup, into a high quality document. For the purpose of analogy, web pages work in a similar way: the HTML is used to describe the document, but it is your browser that presents it in its full glory - with different colours, fonts, sizes, etc.
The input for LaTeX is a plain ASCII text file. You can create it with any text editor. It contains the text of the document, as well as the commands that tell LaTeX how to typeset the text.
For the truly impatient, a minimal example looks something like the following (the commands will be explained later):
\documentclass{article} \begin{document} Hello world! \end{document}
Spaces
"Whitespace" characters, such as blank or tab, are treated uniformly as "space" by LaTeX. Several consecutive whitespace characters are treated as one "space". Whitespace at the start of a line is generally ignored, and a single line break is treated as “whitespace.” An empty line between two lines of text defines the end of a paragraph. Several empty lines are treated the same as one empty line. The text below is an example. On the left hand side is the text from the input file, and on the right hand side is the formatted output.
It does not matter whether you enter one or several spaces after a word. An empty line starts a new paragraph. |
It does not matter whether you enter one or several spaces after a word.
An empty line starts a new paragraph. |
Special Characters
The following symbols are reserved characters that either have a special meaning under LaTeX or are unavailable in all the fonts. If you enter them directly in your text, they will normally not print, but rather make LaTeX do things you did not intend.
# $ % ^ & _ { } ~ \
As you will see, these characters can be used in your documents all the same by adding a prefix backslash:
\# \$ \% \^ \& \_ \{ \} \~ \textbackslash
The other symbols and many more can be printed with special commands in mathematical formulae or as accents. The backslash character \ can not be entered by adding another backslash in front of it (\\); this sequence is used for line breaking. For introducing a backslash in math mode, you can use \backslash instead. The command \~ produces a tilde which is placed over the next letter. For example \~n gives ñ. To produce just the character ~, use \~{} which places a ~ over an empty box.
If you want to insert text that might contain several particular symbols (such as URIs), you can consider using the \verb command, that will be discussed later in the section on formatting.
LaTeX Commands
LaTeX commands are case sensitive, and take one of the following two formats:
- They start with a backslash \ and then have a name consisting of letters only. Command names are terminated by a space, a number or any other "non-letter".
- They consist of a backslash \ and exactly one non-letter.
Some commands need a parameter, which has to be given between curly braces { } after the command name. Some commands support optional parameters, which are added after the command name in square brackets [ ]. The general syntax is:
\commandname[option1,option2,...]{argument1}{argument2}...
LaTeX environments
Environments in LaTeX have a role that is quite similar to commands, but they usually have effect on a wider part of the document. Their syntax is:
\begin{environmentname} text to be influenced \end{environmentname}
between the \begin and the \end you can put other commands and nested environments. In general, environments can accept arguments as well, but this feature is not commonly used and so it will be discussed in more advanced parts of the document.
Anything in LaTeX can be expressed in terms of commands and environments.
Comments
When LaTeX encounters a % character while processing an input file, it ignores the rest of the present line, the line break, and all whitespace at the beginning of the next line.
This can be used to write notes into the input file, which will not show up in the printed version.
This is an % stupid % Better: instructive <---- example: Supercal% ifragilist% icexpialidocious |
This is an example: Supercalifragilisticexpialidocious |
The % character can also be used to split long input lines where no whitespace or line breaks are allowed.
Input File Structure
When LaTeX processes an input file, it expects it to follow a certain structure. Thus every input file must start with the command
\documentclass{...}
This specifies what sort of document you intend to write. After that, you can include commands that influence the style of the whole document, or you can load packages that add new features to the LaTeX system. To load such a package you use the command
\usepackage{...}
When all the setup work is done, you start the body of the text with the command
\begin{document}
Now you enter the text mixed with some useful LaTeX commands. At the end of the document you add the
\end{document}
command, which tells LaTeX to call it a day. Anything that follows this command will be ignored by LaTeX. The area between \documentclass and \begin{document} is called the preamble.
A Typical Command Line Session
LaTeX itself does not have a GUI (graphical user interface), since it is just a program that crunches away at your input files, and produces either a DVI or PDF file. Some LaTeX installations feature a graphical front-end where you can click LaTeX into compiling your input file. On other systems there might be some typing involved, so here is how to coax LaTeX into compiling your input file on a text based system. Please note: this description assumes that a working LaTeX installation already sits on your computer.
- Edit/Create your LaTeX input file. This file must be plain ASCII text. On Unix all the editors will create just that. On Windows you might want to make sure that you save the file in ASCII or Plain Text format. When picking a name for your file, make sure it bears a .tex extension.
- Run LaTeX on your input file. If successful you will end up with a .dvi file. It may be necessary to run LaTeX several times to get the table of contents and all internal references right. When your input file has a bug LaTeX will tell you about it and stop processing your input file.
Type ctrl-D to get back to the command line.
latex foo.tex
Now you may view the DVI file. On Unix with X11 you can type xdvi foo.dvi, on Windows you can use a program called yap (yet another previewer).
You can run a similar procedure with pdflatex to produce a PDF document from the original tex source. Similar to above, type the commands:
pdflatex foo.tex
Now you may view the PDF file, foo.pdf.
Our first document
Now we can create our first document. We will produce the absolute bare minimum that is needed in order to get some output; the well known Hello World! approach will be suitable here.
- Open your favourite text-editor. If you use vim or emacs, they also have syntax highlighting that will help to write your files.
- Reproduce the following text in your editor. This is the LaTeX source.
% hello.tex - Our first LaTeX example! \documentclass{article} \begin{document} Hello World! \end{document}
- Save your file as hello.tex.
What does it all mean?
% hello.tex - Our first LaTeX example! |
The first line is a comment. This is because it begins with the percent symbol (%); when LaTeX sees this, it simply ignores the rest of the line. Comments are useful for humans to annotate parts of the source file. For example, you could put information about the author and the date, or whatever you wish. |
\documentclass{article} |
This line is a command and tells LaTeX to use the article document class. A document class file defines the formatting, which in this case is a generic article format. The handy thing is that if you want to change the appearance of your document, substitute article for another class file that exists. |
\begin{document} |
This line is the beginning of the environment called document; it alerts LaTeX that content of the document is about to commence. Anything above this command is known generally to belong in the preamble. |
Hello World! |
This was the only actual line containing real content - the text that we wanted displayed on the page. |
\end{document} |
The document environment ends here. It tells LaTeX that the document source is complete, anything after this line will be ignored. |
As we have said before, each of the LaTeX commands begin with a backslash (\). This is LaTeX's way of knowing that whenever it sees a backslash, to expect some commands. Comments are not classed as a command, since all they tell LaTeX is to ignore the line. Comments never affect the output of the document.
Generating the document
It is clearly not going to be the most exciting document you have ever seen, but we want to see it nonetheless. I am assuming that you are at a command prompt, already in the directory where hello.tex is stored.
- Type the command:
latex hello(the .tex extension is not required, although you can include it if you wish) - Various bits of info about LaTeX and its progress will be displayed. If all went well, the last two lines displayed in the console will be:
Output written on hello.dvi (1 page, 232 bytes). Transcript written on hello.log.
This means that your source file has been processed and the resulting document is called hello.dvi, which takes up 1 page and 232 bytes of space. This way you created the DVI file, but with the same source file you can create a PDF document. The steps are exactly the same as before, but you have to replace the command latex with pdflatex:
- Type the command:
pdflatex hello(as before, the .tex extension is not required) - Various bits of info about LaTeX and its progress will be displayed. If all went well, the last two lines displayed in the console will be:
Output written on hello.pdf (1 page, 5548 bytes). Transcript written on hello.log.
you can notice that the PDF document is bigger than the DVI, even if it contains exactly the same information. The main differences between the DVI and PDF formats are:
- DVI needs less disk space and it is faster to create. It does not include the fonts within the document, so if you want the document to be viewed properly on another computer, there must be all the necessary fonts installed. It does not support any interactivity such as hyperlinks or animated images. DVI viewers are not very common, so you can consider using it for previewing your document while typesetting.
- PDF needs more disk space and it is slower to create, but it includes all the necessary fonts within the document, so you will not have any problem of portability. It supports internal and external hyperlinks. Nowadays it is the de facto standard for sharing and publishing documents, so you can consider using it for the final version of your document.
About now, you saw you can create both DVI and PDF document from the same source. This is true, but it gets a bit more complicated if you want to introduce images or links. This will be explained in detail in the next chapters, about now assume you can compile in both DVI and PDF without any problem.
Note, in this instance, due to the simplicity of the file, you only need to run the LaTeX command once. However, if you begin to create complex documents, including bibliographies and cross-references, etc, LaTeX needs to be executed multiple times to resolve the references. But this will be discussed in the future when it comes up.
Basics
Document Classes
The first information LaTeX needs to know when processing an input file is the type of document the author wants to create. This is specified with the \documentclass command.
\documentclass[options]{class}
Here class specifies the type of document to be created. The LaTeX distribution provides additional classes for other documents, including letters and slides. The options parameter customizes the behavior of the document class. The options have to be separated by commas.
Example: an input file for a LaTeX document could start with the line
\documentclass[11pt,twoside,a4paper]{article}
which instructs LaTeX to typeset the document as an article with a base font size of eleven points, and to produce a layout suitable for double sided printing on A4 paper.
Here are some document classes that can be used with LaTeX:
| article | for articles in scientific journals, presentations, short reports, program documentation, invitations, ... |
| proc | a class for proceedings based on the article class. |
| minimal | is as small as it can get. It only sets a page size and a base font. It is mainly used for debugging purposes. |
| report | for longer reports containing several chapters, small books, thesis, ... |
| book | for real books |
| slides | for slides. The class uses big sans serif letters. |
| memoir | for changing sensibly the output of the document. It is based on the book class, but you can create any kind of document with it [9] |
| letter | for writing letters. |
| beamer | for writing presentations (see LaTeX/Presentations). |
The most common options for the standard document classes are listed in the following table:
| 10pt, 11pt, 12pt | Sets the size of the main font in the document. If no option is specified, 10pt is assumed. |
| a4paper, letterpaper,... | Defines the paper size. The default size is letterpaper; However, many European distributions of TeX now come pre-set for A4, not Letter, and this is also true of all distributions of pdfLaTeX. Besides that, a5paper, b5paper, executivepaper, and legalpaper can be specified. |
| fleqn | Typesets displayed formulas left-aligned instead of centered. |
| leqno | Places the numbering of formulae on the left hand side instead of the right. |
| titlepage, notitlepage | Specifies whether a new page should be started after the document title or not. The article class does not start a new page by default, while report and book do. |
| onecolumn, twocolumn | Instructs LaTeX to typeset the document in one column or two columns. |
| twoside, oneside | Specifies whether double or single sided output should be generated. The classes article and report are single sided and the book class is double sided by default. Note that this option concerns the style of the document only. The option twoside does not tell the printer you use that it should actually make a two-sided printout. |
| landscape | Changes the layout of the document to print in landscape mode. |
| openright, openany | Makes chapters begin either only on right hand pages or on the next page available. This does not work with the article class, as it does not know about chapters. The report class by default starts chapters on the next page available and the book class starts them on right hand pages. |
| draft | makes LaTeX indicate hyphenation and justification problems with a small square in the right-hand margin of the problem line so they can be located quickly by a human. |
For example, if you want a report to be in 12pt type on A4, but printed one-sided in draft mode, you would use:
\documentclass[12pt,a4paper,oneside,draft]{report}
Packages
While writing your document, you will probably find that there are some areas where basic LaTeX cannot solve your problem. If you want to include graphics, colored text or source code from a file into your document, you need to enhance the capabilities of LaTeX. Such enhancements are called packages. Packages are activated with the
\usepackage[options]{package}
command, where package is the name of the package and options is a list of keywords that trigger special features in the package. Some packages come with the LaTeX base distribution. Others are provided separately.
Modern TeX distributions come with a large number of packages pre-installed. If you are working on a Unix system, use the command texdoc for accessing package documentation. For more information, see the Packages section.
Files you might Encounter
When you work with LaTeX you will soon find yourself in a maze of files with various extensions and probably no clue. The following list explains the most common file types you might encounter when working with TeX:
| .aux | A file that transports information from one compiler run to the next. Among other things, the .aux file is used to store information associated with cross-references. |
| .bbl | Bibliography file output by BiBTeX and used by LaTeX |
| .bib | Bibliography database file |
| .blg | BiBTeX log file. |
| .bst | BiBTeX style file. |
| .cls | Class files define what your document looks like. They are selected with the \documentclass command. |
| .dtx | Documented TeX. This is the main distribution format for LaTeX style files. If you process a .dtx file you get documented macro code of the LaTeX package contained in the .dtx file. |
| .ins | The installer for the files contained in the matching .dtx file. If you download a LaTeX package from the net, you will normally get a .dtx and a .ins file. Run LaTeX on the .ins file to unpack the .dtx file. |
| .fd | Font description file telling LaTeX about new fonts. |
| .dvi | Device Independent File. This is the main result of a LaTeX compile run with latex. You can look at its content with a DVI previewer program or you can send it to a printer with dvips or a similar application. |
| Portable Document Format. This is the main result of a LaTeX compile run with pdflatex. You can look at its content or print it with any PDF viewer. | |
| .log | Gives a detailed account of what happened during the last compiler run. |
| .toc | Stores all your section headers. It gets read in for the next compiler run and is used to produce the table of contents. |
| .lof | This is like .toc but for the list of figures. |
| .lot | And again the same for the list of tables. |
| .idx | If your document contains an index. LaTeX stores all the words that go into the index in this file. Process this file with makeindex. |
| .ind | The processed .idx file, ready for inclusion into your document on the next compile cycle. |
| .ilg | Logfile telling what makeindex did. |
| .sty | LaTeX Macro package. This is a file you can load into your LaTeX document using the \usepackage command. |
| .tex | LaTeX or TeX input file. It can be compiled with latex. |
Big Projects
When working on big documents, you might want to split the input file into several parts. LaTeX has three commands to insert a file into another when building the document.
The simplest is the \input command:
\input{filename}
\input inserts the contents of another file, named filename.tex; note that the .tex extension is omitted. For all practical purposes, \input is no more than a simple, automated cut-and-paste of the source code in filename.tex.
The other main inclusion command is \include:
\include{filename}
The \include command is different from \input in that it's the output that is added instead of the commands from the other files. Therefore a new page will be created at every \include command, which makes it appropriate to use it for large entities such as book chapters.
Very large documents (that usually include many files) take a very long time to compile, and most users find it convenient to test their last changes by including only the files they have been working on. One option is to hunt down all \include commands in the inclusion hierarchy and to comment them out:
%\include{filename1} \include{filename2} \include{filename3} %\include{filename4}
In this case, the user wants to include only filename2.tex and filename3.tex. If the inclusion hierarchy is intricate, commenting can become error-prone: page numbering will change, and any cross references won't work. A better alternative is to retain the include calls and use the \includeonly command in the preamble:
\includeonly{filename2,filename3}
This way, only \include commands for the specified files will be executed, and inclusion will be handled in only one place. Note that there must be no spaces between the filenames and the commas.
Picking suitable filenames
Never, ever use directories (folders) or file names that contain spaces. Although your operating system probably 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 letters without accents (a-z), the digits 0-9, the hyphen (-), and the full point or period (.), (similar to the conventions for a Web URL): it will let you refer to TeX files over the Web more easily and make your files more portable. Some operating systems do not distinguish between upper-case and lower-case letters, others do. Therefore it's best not to mix them.
Working in a team
See chapter Collaborative Writing of LaTeX Documents.
Document Structure
The main point of writing a text is to convey ideas, information, or knowledge to the reader. The reader will understand the text better if these ideas are well-structured, and will see and feel this structure much better if the typographical form reflects the logical and semantic structure of the content.
LaTeX is different from other typesetting systems in that you just have to tell it the logical and semantical structure of a text. It then derives the typographical form of the text according to the “rules” given in the document class file and in various style files. LaTeX allows users to structure their documents with a variety of hierarchal constructs, including chapters, sections, subsections and paragraphs.
The document environment
After the Document Class Declaration, the text of your document is enclosed between two commands which identify the beginning and end of the actual document:
\documentclass[11pt,a4paper,oneside]{report} \begin{document} ... \end{document}
You would put your text where the dots are. The reason for marking off the beginning of your text is that LaTeX allows you to insert extra setup specifications before it (where the blank line is in the example above: we'll be using 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, like making an index.
A useful side-effect of marking the end of the document text is that you can store comments or temporary text underneath the \end{document} in the knowledge that LaTeX will never try to typeset them:
... \end{document} Don't forget to get the extra chapter from Dorando!
Preamble
The preamble is everything from the start of the Latex source file until the \begin{document} command. It normally contains commands that affect the entire document.
% simple.tex - A simple article to illustrate document structure. \documentclass{article} \usepackage{mathptmx} \begin{document}
The first line is a comment (as denoted by the % sign). The \documentclass command takes an argument, which in this case is article, because that's the type of document we want to produce. It is also possible to create your own, as is often done by journal publishers, who simply provide you with their own class file, which tells Latex how to format your content. But we'll be happy with the standard article class for now! \usepackage is an important command that tells Latex to utilize some external macros. In this instance, we specified mathptmx which means Latex will use the Postscript Times type 1 font instead of the default ComputerModern font. And finally, the \begin{document}. This strictly isn't part of the preamble, but I'll put it here anyway, as it implies the end of the preamble by nature of stating that the document is now starting.
Top Matter
At the beginning of most documents there will be information about the document itself, such as the title and date, and also information about the authors, such as name, address, email etc. All of this type of information within Latex is collectively referred to as top matter. Although never explicitly specified (there is no \topmatter command) you are likely to encounter the term within Latex documentation.
A simple example:
\documentclass[11pt,a4paper,oneside]{report} \begin{document} \title{How to Structure a LaTeX Document} \author{Andrew Roberts} \date{December 2004} \maketitle \end{document}
The \title, \author, and \date commands are self-explanatory. You put the title, author name, and date in curly braces after the relevant command. The title and author are usually compulsory (at least if you want LaTeX to write the title automatically); if you omit the \date command, LaTeX uses today's date by default. You always finish the top matter with the \maketitle command, which tells LaTeX that it's complete and it can typeset the title according to the information you have provided and the class (style) you are using. If you omit \maketitle, the titling will never be typeset (unless you write your own).
Here is a more complicated example:
\title{How to Structure a \LaTeX{} Document} \author{Andrew Roberts\\ School of Computing,\\ University of Leeds,\\ Leeds,\\ United Kingdom,\\ LS2 1HE\\ \texttt{andyr@comp.leeds.ac.uk}} \date{\today} \maketitle
as you can see, you can use commands as arguments of \title and the others. The double backslash (\\) is the LaTeX command for forced linebreak. LaTeX normally decides by itself where to break lines, and it's usually right, but sometimes you need to cut a line short, like here, and start a new one.
If there are two authors separate them with the \and command.
\title{Our Fun Document} \author{Jane Doe \and John Doe} \date{\today} \maketitle
If you are provided with a class file from a publisher, or if you use the AMS article class (amsart), then you can use several different commands to enter author information. The email address is at the end, and the \texttt commands formats the email address using a mono-spaced font. The built-in command called \today will be replaced with the current date when processed by LaTeX. But you are free to put whatever you want as a date, in no set order. If braces are left empty, then the date is omitted.
Using this approach, you can create only basic output whose layout is very hard to change. If you want to create your title freely, see the Title Creation section.
Abstract
As most research papers have an abstract, there are predefined commands for telling LaTeX which part of the content makes up the abstract. This should appear in its logical order, therefore, after the top matter, but before the main sections of the body. This command is available for the document class article and report, but not book.
\documentclass{article} \begin{document} \begin{abstract} Your abstract goes here... ... \end{abstract} ... \end{document}
By default, LaTeX will use the word "Abstract" as a title for your abstract, if you want to change it into anything else, e.g. "Executive Summary", add the following line in the preamble:
\renewcommand{\abstractname}{Executive Summary}
Sectioning Commands
The commands for inserting sections are fairly intuitive. Of course, certain commands are appropriate to different document classes. For example, a book has chapters but an article doesn't. Here is an edited version of some of the structure commands in use from simple.tex.
\section{Introduction} This section's content... \section{Structure} This section's content... \subsection{Top Matter} This subsection's content... \subsubsection{Article Information} This subsubsection's content...
As you can see, the commands are fairly intuitive. Notice that you do not need to specify section numbers. LaTeX will sort that out for you! Also, for sections, you do not need to markup which content belongs to a given block, using \begin and \end commands, for example. LaTeX provides 7 levels of depth for defining sections:
| Command | Level | Comment |
|---|---|---|
| \part{part} | -1 | not in letters |
| \chapter{chapter} | 0 | only books and reports |
| \section{section} | 1 | not in letters |
| \subsection{subsection} | 2 | not in letters |
| \subsubsection{subsubsection} | 3 | not in letters |
| \paragraph{paragraph} | 4 | not in letters |
| \subparagraph{subparagraph} | 5 | not in letters |
All the titles of the sections are added automatically to the table of contents (if you decide to insert one). But if you make manual styling changes to your heading, for example a very long title, or some special line-breaks or unusual font-play, this would appear in the Table of Contents as well, which you almost certainly don't want. LaTeX allows you to give an optional extra version of the heading text which only gets used in the Table of Contents and any running heads, if they are in effect. This optional alternative heading goes in [square brackets] before the curly braces:
\section[Effect on staff turnover]{An analysis of the effect of the revised recruitment policies on staff turnover at divisional headquarters}
Section numbering
Numbering of the sections is performed automatically by LaTeX, so don't bother adding them explicitly, just insert the heading you want between the curly braces. Parts get roman numerals (Part I, Part II, etc.); chapters and sections get decimal numbering like this document, and appendices (which are just a special case of chapters, and share the same structure) are lettered (A, B, C, etc.). You can change the depth to which section numbering occurs, so you can turn it off selectively. By default it is set to 2. If you only want parts, chapters, and sections numbered, not subsections or subsubsections etc., you can change the value of the secnumdepth counter using the \setcounter command, giving the depth level from the previous table. For example, if you want to change it to "1":
\setcounter{secnumdepth}{1}
A related counter is tocdepth, which specifies what depth to take the Table of Contents to. It can be reset in exactly the same way as secnumdepth. For example:
\setcounter{tocdepth}{3}
To get an unnumbered section heading which does not go into the Table of Contents, follow the command name with an asterisk before the opening curly brace:
\subsection*{Introduction}
All the divisional commands from \part* to \subparagraph* have this "starred" version which can be used on special occasions for an unnumbered heading when the setting of secnumdepth would normally mean it would be numbered.
If you want the unnumbered section to be in the table of contents anyway, use the \addcontentsline command like this:
\section*{Introduction} \addcontentsline{toc}{section}{Introduction}
The value where the section numbering starts from can be set with the following command:
\setcounter{section}{4}
The next section after this command will now be numbered 5.
Appendices
The separate numbering of appendices is also supported by LaTeX. The \appendix macro can be used to indicate that following sections or chapters are to be numbered as appendices.
In the report or book classes this gives:
\appendix \chapter{First Appendix}
For the article class use:
\appendix \section{First Appendix}
Ordinary paragraphs
After section headings comes your text. Just type it and leave a blank line between paragraphs. That's all LaTeX needs. The blank line means "start a new paragraph here": it does not mean you get a blank line in the typeset output. The spacing between paragraphs is a separately definable quantity, a dimension or length called \parskip. This is normally zero (no space between paragraphs, because that's how books are normally typeset), but you can easily set it to any size you want with the \setlength command in the Preamble:
\setlength{\parskip}{1cm}
This will set the space between paragraphs to 1cm. Leaving multiple blank lines between paragraphs in your source document achieves nothing: all extra blank lines get ignored by LaTeX because the space between paragraphs is controlled only by the value of \parskip.
White-space in LaTeX can also be made flexible (what Lamport calls "rubber" lengths). This means that values such as \parskip can have a default dimension plus an amount of expansion minus an amount of contraction. This is 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:
\setlength{\parskip}{1cm plus4mm minus3mm}
Paragraph indentation can also be set with the \setlength command, although you would always make it a fixed size, never a flexible one, otherwise you would have very ragged-looking paragraphs.
\setlength{\parindent}{6mm}
By default, the first paragraph after a heading follows the standard Anglo-American publishers' practice of no indentation. Subsequent paragraphs are indented by the value of \parindent (default 18pt). You can change this in the same way as any other length.
To turn off indentation completely, set it to zero (but you still have to provide units: it's still a measure!).
\setlength{\parindent}{0in}
If you do this, though, and leave \parskip set to zero, your readers won't be able to tell easily where each paragraph begins! If you want to use the style of having no indentation with a space between paragraphs, use the parskip package, which does it for you (and makes adjustments to the spacing of lists and other structures which use paragraph spacing, so they don't get too far apart).
Table of contents
All auto-numbered headings get entered in the Table of Contents (ToC) automatically. You don't have to print a ToC, but if you want to, just add the command \tableofcontents at the point where you want it printed (usually after the Abstract or Summary).
Entries for the ToC are recorded each time you process your document, and reproduced the next time you process it, so you need to re-run LaTeX one extra time to ensure that all ToC pagenumber references are correctly calculated. We've already seen how to use the optional argument to the sectioning commands to add text to the ToC which is slightly different from the one printed in the body of the document. It is also possible to add extra lines to the ToC, to force extra or unnumbered section headings to be included.
The commands \listoffigures and \listoftables work in exactly the same way as \tableofcontents to automatically list all your tables and figures. If you use them, they normally go after the \tableofcontents command. The \tableofcontents command normally shows only numbered section headings, and only down to the level defined by the tocdepth counter, but you can add extra entries with the \addcontentsline command. For example if you use an unnumbered section heading command to start a preliminary piece of text like a Foreword or Preface, you can write:
\subsection*{Preface} \addcontentsline{toc}{subsection}{Preface}
This will format an unnumbered ToC entry for "Preface" in the "subsection" style. You can use the same mechanism to add lines to the List of Figures or List of Tables by substituting lof or lot for toc.
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:
\setcounter{tocdepth}{4}
This will make the table of contents include everything down to paragraphs. The levels are defined above on this page.
The Bibliography
Any good research paper will have a whole list of references. There are two ways to insert your references into LaTeX:
- you can embed them within the document itself. It's simpler, but it can be time-consuming if you are writing several papers about similar subjects so that you often have to cite the same books.
- you can store them in an external BibTeX file and then link them via a command to your current document and use a Bibtex style to define how they appear. This way you can create a small database of the references you might use and simply link them, letting LaTeX work for you.
In order to know how to add the bibliography to your document, see the Bibliography Management section.
Errors and Warnings
LaTeX describes what it's typesetting while it does it, and if it encounters something it doesn't understand or can't do, it will display a message saying what's wrong. It may also display warnings for less serious conditions.
Don't panic if you see error messages: it's very common to mistype or mis-spell commands, forget curly braces, type a forward slash instead of a backslash, or use a special character by mistake. Errors are easily spotted and easily corrected in your editor, and you can then run LaTeX again to check you have fixed everything. Some of the most common errors are described in next sections.
Error messages
The format of an error message is always the same. Error messages begin with an exclamation mark at the start of the line, and give a description of the error, followed by another line starting with the number, which refers to the line-number in your document file which LaTeX was processing when the error was spotted. Here's an example, showing that the user mistyped the \tableofcontents command:
! Undefined control sequence. l.6 \tableofcontents
When LaTeX finds an error like this, it displays the error message and pauses. You must type one of the following letters to continue:
| Key | Meaning |
|---|---|
| x | Stop immediately and exit the program. |
| q | Carry on quietly as best you can and don't bother me with any more error messages. |
| e | Stop the program but re-position the text in my editor at the point where you found the error (This only works if you're using an editor which LaTeX can communicate with). |
| h | Try to give me more help. |
| i | (followed by a correction) means input the correction in place of the error and carry on (This is only a temporary fix to get the file processed. You still have to make that correction in the editor). |
| r | run in non-stop mode. Plow through any errors, unless too many pile up and it fails (100 errors). |
Some systems (Emacs is one example) run LaTeX with 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.
Warnings
Warnings don't begin with an exclamation mark: they are just comments by LaTeX about things you might want to look into, such as overlong or underrun lines (often caused by unusual hyphenations, for example), pages running short or long, and other typographical niceties (most of which you can ignore until later). Unlike other systems, which try to hide unevennesses in the text (usually unsuccessfully) by interfering with the letterspacing, LaTeX takes the view that the author or editor should be able to contribute. While it is certainly possible to set LaTeX's parameters so that the spacing is sufficiently sloppy that you will almost never get a warning about badly-fitting lines or pages, you will almost certainly just be delaying matters until you start to get complaints from your readers or publishers.
Examples
Only a few common error messages are given here: those most likely to be encountered by beginners. If you find another error message not shown here, and it's not clear what you should do, ask for help.
Most error messages are self-explanatory, but be aware that the place where LaTeX spots and reports an error may be later in the file than the place where it actually occurred. For example if you forget to close a curly brace which encloses, say, italics, LaTeX won't report this until something else occurs which can't happen until the curly brace is encountered (e.g. the end of the document!) Some errors can only be righted by humans who can read and understand what the document is supposed to mean or look like.
Newcomers should remember to check the list of special characters: a very large number of errors when you are learning LaTeX are due to accidentally typing a special character when you didn't mean to. This disappears after a few days as you get used to them.
Too many }'s
! Too many }'s. l.6 \date December 2004}
The reason LaTeX thinks there are too many }'s here is that the opening curly brace is missing after the \date control sequence and before the word December, so the closing curly brace is seen as one too many (which it is!). In fact, there are other things which can follow the \date command apart from a date in curly braces, so LaTeX cannot possibly guess that you've missed out the opening curly brace until it finds a closing one!
Undefined control sequence
! Undefined control sequence.
l.6 \dtae
{December 2004}
In this example, LaTeX is complaining that it has no such command ("control sequence") as \dtae. Obviously it's been mistyped, but only a human can detect that fact: all LaTeX knows is that \dtae is not a command it knows about: it's undefined. Mistypings are the most common source of errors. If your editor has drop-down menus to insert common commands and environments, use them!
Runaway argument
Runaway argument?
{December 2004 \maketitle
! Paragraph ended before \date was complete.
<to be read again>
\par
l.8
In this error, the closing curly brace has been omitted from the date. It's the opposite of the error of too many }'s, and it results in \maketitle trying to format the title page while LaTeX is still expecting more text for the date! As \maketitle creates new paragraphs on the title page, this is detected and LaTeX complains that the previous paragraph has ended but \date is not yet finished.
Underfull hbox
Underfull \hbox (badness 1394) in paragraph at lines 28--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 currently permitted maximum. The badness (0-10,000) indicates how severe this is (here you can probably ignore a badness of 1394). It says what lines of your file it was typesetting when it found this, and the number in square brackets is the number of the page onto which the offending line was printed. The codes separated by slashes are the typeface and font style and size used in the line. Ignore them for the moment.
This comes up if you force a linebreak, e.g., \\, and have a return before it. Normally tex ignores linebreaks, providing full paragraphs to ragged text. In this case it is necessary to pull the linebreak up one line to the end of the previous sentence.
Overfull hbox
[101] Overfull \hbox (9.11617pt too wide) in paragraph at lines 860--861 []\LY1/brm/m/n/10 Windows, \LY1/brm/m/it/10 see \LY1/brm/m/n/10 X Win-
And the opposite warning: this line is too long by a shade over 9pt. The chosen hyphenation point which minimizes the error is shown at the end of the line (Win-). Line numbers and page numbers are given as before. In this case, 9pt is too much to ignore (over 3mm), and a manual correction needs making (such as a change to the hyphenation), or the flexibility settings need changing.
If the "overfull" word includes a forward slash, such as "input/output", this should be properly typeset as "input\slash output". The use of \slash has the same effect as using the "/" character, except that it can form the end 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 broken over multiple lines.
Overfull \hbox means that the output file goes over the edge. The code line being refered (in this case: 860-861) outputs to the right of the page, so it might not be displayed (and eventually printed) properly. Try adjusting the line so it is broken down in to 2 or more lines.
Missing package
! LaTeX Error: File paralisy.sty not found. Type X to quit or <RETURN> to proceed, or enter new name. (Default extension: sty) Enter file name:
When you use the \usepackage command to request LaTeX to use a certain package, it will look for a file with the specified name and the filetype .sty. In this case the user has mistyped the name of the paralist package, so it's easy to fix. However, if you get the name right, but the package is not installed on your machine, you will need to download and install it before continuing. If you don't want to affect the global installation of the machine, you can simply download from Internet the necessary .sty file and put it in the same folder of the document you are compiling.
Package babel Warning: No hyphenation patterns were loaded for the language X
Although this is a warning from the Babel package and not from LaTeX, this error is very common and (can) give some strange hyphenation (word breaking) problems in your document. Wrong hyphenation rules can decrease the neatness of your document.
Package babel Warning: No hyphenation patterns were loaded for (babel) the language `Latin' (babel) I will use the patterns loaded for \language=0 instead.
This can happen after the usage of: (see LaTeX/Internationalization)
\usepackage[latin]{babel}
The solution is not difficult, just install the used language in your LaTeX distribution.
Title Creation
There are several situations where you might want to vary the title from its default format. For shorter documents such as basic articles, the output of \maketitle is often adequate, but longer documents (such as books and reports) often require more involved formatting. While it is possible to change the output of \maketitle, it can be complicated even with minor changes to the title. In such cases it is often better to create the title from scratch.
Standard Title Pages
Many document classes will form a title page for you. One must specify what to fill it with using these commands:
\title{The Triangulation of Titling Data in Non-Linear Gaussian Fashion via $\rho$ Series} \date{October 31, 475} \author{John Doe\\ Magic Department, Richard Miles University \and Richard Row, LaTeX Academy}
Commonly the date is excluded from the title page by using \date{}. It defaults to \today if not in the source file.
To form a title page, use
\maketitle
This should go after the preceding commands. For most document styles, this will form a separate page, while the article document style will place the title on the top of the first page. Note that the abstract environment should precede the \maketitle command in AMS documents.
Footnotes within the title page can be specified with the \thanks command. For example, one may add
\author{John Doe\thanks{Funded by NASA Grant #42}}
The \thanks command can also be used in the \title too.
It is dependent on the document class which commands are used in the title page generated by \maketitle. For example, the amsart uses commands such as \address, \dedicatory, \email and more in the title page while other classes may only use \title.
Custom Title Pages
Create the title
Normally, the benefit of using LaTeX instead of traditional word processing programs is that LaTeX frees you to concentrate on content by handling margins, justification, and other typesetting concerns. On the other hand, if you want to write your own title format, it is exactly the opposite: you have to take care of everything--this time LaTeX will do nothing to help you. It can be challenging to create your own title format since LaTeX was not designed to be graphically interactive in the adjustment of layout. The process is similar to working with raw HTML with the added step that each time you want to see how your changes look, you have to re-compile the source. While this may seem like a major inconvenience, the benefit is that once the customized title format has been written, it serves as a template for all other documents that would use the title format you have just made. In other words, once you have a layout you like, you can use it for any other documents where you would like the same layout without any additional fiddling with layout.
First step: since you'll be working only on the first page of your document and you'll have to compile very often, you don't have to compile the whole document each time, you only need to take a look at the first page. That is why we'll first create a dummy document for preparing the title and then we'll simply include it within the existing big document we are writing. Call the dummy document test_title.tex and put the following code in it:
\documentclass[pdftex,12pt,a4paper]{report} \usepackage[pdftex]{graphicx} \newcommand{\HRule}{\rule{\linewidth}{0.5mm}} \begin{document} \input{./title.tex} \end{document}
It is meant to be compiled with pdflatex to create a PDF in output. It is a very basic document, but take care that it has the same settings of the document you are writing, so the output won't change when you include the title in your document. In this case (see the first line) the font size is set to 12pt and the paper size is an A4. The package graphicx is included to insert an image in the title. Then a command is defined called \HRule; it will just insert a horizontal line whose length is like the size of the paper and whose thickness is 0.5 mm. If you want you can change its settings in the definition. Finally the document starts and it simply includes the title.tex file, that must be placed in the same directory of our dummy file test_title.tex.
Now create the title.tex and write in it:
\begin{titlepage} \end{titlepage}
all the things you want to put in the title must be inside the titlepage environment. Now if you compile test_title.tex you will see a preview of your title in the test_title.pdf file. Here is what you need to know to write your title:
- Alignment
- if you want to center some text just use
\begin{center} ... \end{center}. If you want to align it differently you can use the environmentflushrightfor right-alignment andflushleftfor left alignment. - Images
- the command for including images is the following (the example is for a small logo, but you can introduce any image of any size):
\includegraphics[width=0.15\textwidth]{./logo}. There is no\begin{figure}as you usually do because you don't want it to be floating, you just want it there where you placed it. When handling it, remember that it is considered like a big box by the TeX engine. - Text size
- If you want to change the size of some text just place it within brackets, {like this}, and you can use the following commands (in order of size):
\Huge,\huge,\LARGE,\Large,\large,\small,\footnotesize,\tiny. So for example:{\large this text is slightly bigger than normal}, this one is not
\normalsizeis used to create text at the default size for the document.- New lines
- you can force the start of a new line by
\\. If you want to add more vertical space you don't need to use several new-line commands, just insert some vertical space. For example, this way\\[1cm]you start a new line after having left 1 cm of empty space. - Date
- you can insert the date of the current day with the command
\today. - Filling the page
- the command
\vfillkeeps on adding empty spaces until the page is full. If you put it in the page, you are sure that all the following text will be placed at the bottom of the page.
A practical example
All these tips might have made you confused. Then, here is a practical example. Get the test_title.tex described above and here is an example of a title.tex. On the right you can see the output after you compile test_title.tex in PDF:
\begin{titlepage} \begin{center} % Upper part of the page \includegraphics[width=0.15\textwidth]{./logo}\\[1cm] \textsc{\LARGE University of Beer}\\[1.5cm] \textsc{\Large Final year project}\\[0.5cm] % Title \HRule \\[0.4cm] { \huge \bfseries Lager brewing techniques}\\[0.4cm] \HRule \\[1.5cm] % Author and supervisor \begin{minipage}{0.4\textwidth} \begin{flushleft} \large \emph{Author:}\\ John \textsc{Smith} \end{flushleft} \end{minipage} \begin{minipage}{0.4\textwidth} \begin{flushright} \large \emph{Supervisor:} \\ Dr. Mark \textsc{Brown} \end{flushright} \end{minipage} \vfill % Bottom of the page {\large \today} \end{center} \end{titlepage} |
The picture is from a file called logo.png that is in the same directory of both title.tex and test_title.tex. Since I wanted to insert both the author and supervisor names properly aligned I used a trick: I created two small minipages, one on left and one on the right. Their width is a bit less than half of page width (as you can see, they are exactly 40% of the text width). Within the minipages I have used different alignments. Using \vfill I could write the date exactly at the bottom of the page.
As you can see, the code looks "dirtier" than standard LaTeX source because you have to take care of the output as well. If you start changing font's output it will get more confused, but you can do it: it's only for the title and your complicated code will be isolated from all the rest within its own file title.tex.
Insert it in your document
Once you have your title.tex ready, simply place it in the folder of your document and insert it with \input{./title.tex}. Don't forget to add the commands \usepackage[pdftex]{graphicx} and \newcommand{\HRule}{\rule{\linewidth}{0.5mm}}, otherwise you might get an error. So the beginning of your document should look like:
... \usepackage[pdftex]{graphicx} \newcommand{\HRule}{\rule{\linewidth}{0.5mm}} \begin{document} \input{./title.tex} \tableofcontents ...
Bibliography Management
For any academic/research writing, incorporating references into a document is an important task. Fortunately, LaTeX has a variety of features that make dealing with references much simpler, including built-in support for citing references. However, a much more powerful and flexible solution is achieved thanks to an auxiliary tool called BibTeX (which comes bundled as standard with LaTeX.)
BibTeX provides for the storage of all references in an external, flat-file database. This database can be linked to any LaTeX document, and citations made to any reference that is contained within the file. This is often more convenient than embedding them at the end of every document written. There is now a centralized bibliography source that can be linked to as 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 references concerning General Relativity and another about Quantum Mechanics. When writing about Quantum Gravity (QG), which tries to bridge the gap between these two theories, both of these files can be linked into the document, in addition to references specific to QG.
Embed system
If you are writing only one or two documents and aren't planning on writing more on the same subject for a long time, maybe you don't want to waste time creating a database of references you are never going to use. In this case you should consider using the basic and simple bibliography support that is embedded within LaTeX.
LaTeX provides an environment called thebibliography that you have to use where you want the bibliography, that usually means at the very end of your document, just before the \end{document} command. Here is a practical example:
\begin{thebibliography}{9} \bibitem{lamport94} Leslie Lamport, \emph{\LaTeX: A Document Preparation System}. Addison Wesley, Massachusetts, 2nd Edition, 1994. \end{thebibliography}
OK, so what is going on here? The first thing to notice is the establishment of the environment. thebibliography is a keyword that LaTeX recognizes as everything between the begin and end tags as being data for the bibliography. The optional argument which I supplied after the begin statement is telling LaTeX how wide the item label will be when printed. Note however, that it is not a literal parameter, i.e the number 9 in this case, but a text width. Therefore, I am effectively telling LaTeX that I will only need reference labels of one character in width, which means no more than nine references in total. If you want more than ten, then input a two-digit number, such as '99' which permits less than 100 references.
Next is the actual reference entry itself. This is prefixed with the \bibitem{cite_key} command. The cite_key should be a unique identifier for that particular reference, and is often some sort of mnemonic consisting of any sequence of letters, numbers and punctuation symbols (although not a comma). I often use the surname of the first author, followed by the last two digits of the year (hence lamport94). If that author has produced more than one reference for a given year, then I add letters after, 'a', 'b', etc. But, you should do whatever works for you. Everything after the key is the reference itself. You need to type it as you want it to be presented. I have put the different parts of the reference, such as author, title, etc., on different lines for readability. These linebreaks are ignored by LaTeX. I wanted the title to be in italics, so I used the \emph{} command to achieve this.
Citations
To actually cite a given document is very easy. Go to the point where you want the citation to appear, and use 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 citation. The advantage here, once again, is that LaTeX looks after the numbering for you. If it were totally manual, then adding or removing a reference would be a real chore, as you would have to re-number all the citations by hand.
Instead of WYSIWYG editors, typesetting systems like TeX or LaTeX \cite{lamport94} can be used.
Referring More Specific
Sometimes you want to refer to a certain page, figure or theorem in a text book. For that you can use the arguments to the \cite command:
\cite[p. 215]{citation01}
The argument, "p. 215", will show up inside the same brackets
Multiple Citations
When a sequence of multiple citations are needed, you should use a single \cite{} command. The citations are then separated by commas. Here's an example:
\cite{citation01,citation02,citation03}
The result will then be shown as citations inside the same brackets.
No Cite
If you only want a reference to appear in the bibliography, but not where it is referenced in the main text, then the \nocite{} command can be used, for example:
Lamport showed in 1995 something... \nocite{lamport95}.
A special version of the command, \nocite{*}, includes all entries from the database, whether they are referenced in the document or not.
BibTeX
I have previously introduced the idea of embedding references at the end of the document, and then using the \cite command to cite them within the text. In this tutorial, I want to do a little better than this method, as it's not as flexible as it could be. Which is why I wish to concentrate on using BibTeX.
A BibTeX database is stored as a .bib file. It is a plain text file, and so can be viewed and edited easily. The structure of the file is also quite simple. An example of a BibTeX entry:
@article{greenwade93,
author = "George D. Greenwade",
title = "The {C}omprehensive {T}ex {A}rchive {N}etwork ({CTAN})",
year = "1993",
journal = "TUGBoat",
volume = "14",
number = "3",
pages = "342--351"
}
Each entry begins with the declaration of the reference type, in the form of @type. BibTeX knows of practically all types you can think of, common ones are: book, article, and for papers presented at conferences, there is inproceedings. In this example, I have referred to an article within a journal.
After the type, you must have a left curly brace '{' to signify the beginning of the reference attributes. The first one follows immediately after the brace, which is the citation key. This key must be unique for all entries in your bibliography. It is this identifier that 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 reference, but there is a loose standard in which you use the author's surname, followed by the year of publication. This is the scheme that I use in this tutorial.
Next, it should be clear that what follows are the relevant fields and data for that particular reference. The field names on the left are BibTeX keywords. They are followed by an equals sign (=) where the value for that field is then placed. BibTeX expects you to explicitly label the beginning and end of each value. I personally use quotation marks ("), however, you also have the option of using curly braces ('{', '}'). But as you will soon see, curly braces have other roles, within attributes, so I prefer not to use them for this job as they can get more confusing.
Remember that each attribute must be followed by a comma to delimit one from another. You do not need to add a comma to the last attribute, since the closing brace will tell BibTeX that there are no more attributes for this entry, although you won't get an error if you do.
It can take a while to learn what the reference types are, and what fields each type has available (and which ones are required or optional, etc). So, look at this entry type reference and also this field reference for descriptions of all the fields. It may be worth bookmarking or printing these pages so that they are easily at hand when you need them.
Authors
BibTeX can be quite clever with names of authors. It can accept names in forename surname or surname, forename. I personally use the former, but remember that the order you input them (or any data within an entry for 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 are compound surnames, for example "John von Neumann". In this form, BibTeX assumes that the last word is the surname, and everything before is the forename, plus any middle names. You must therefore manually tell BibTeX to keep the 'von' and 'Neumann' together. This is achieved easily using curly braces. So the final result would be "John {von Neumann}". This is easily avoided with the surname, forename, since you have a comma to separate the surname from the forename.
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. As we can see from another example:
@book{goossens93,
author = "Michel Goossens and Frank Mittlebach and Alexander Samarin",
title = "The LaTeX Companion",
year = "1993",
publisher = "Addison-Wesley",
address = "Reading, Massachusetts"
}
This book has three authors, and each is separated as described. Of course, when BibTeX processes and outputs this, there will only be an 'and' between the penultimate and last authors, but within the .bib file, it needs the and's so that it can keep track of the individual authors.
Standard templates
- @article
- An article from a magazine or a journal.
- Required fields: author, title, journal, year.
- Optional fields: volume, number, pages, month, note.
- @book
- A published book
- Required fields: author/editor, title, publisher, year.
- Optional fields: volume/number, series, address, edition, month, note.
- @booklet
- A bound work without a named publisher or sponsor.
- Required fields: title.
- Optional fields: author, howpublished, address, month, year, note.
- @conference
- Equal to inproceedings
- Required fields: author, title, booktitle, year.
- Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note.
- @inbook
- A section of a book
- Required fields: author/editor, title, chapter and/or pages, publisher, year.
- Optional fields: volume/number, series, type, address, edition, month, note.
- @incollection
- A section of a book having its own title.
- Required fields: author, title, booktitle, publisher, year.
- Optional fields: editor, volume/number, series, type, chapter, pages, address, edition, month, note.
- @inproceedings
- An article in a conference proceedings.
- Required fields: author, title, booktitle, year.
- Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note.
- @manual
- Technical manual
- Required fields: title.
- Optional fields: author, organization, address, edition, month, year, note.
- @mastersthesis
- Master thesis
- Required fields: author, title, school, year.
- Optional fields: type, address, month, note.
- @misc
- Template useful for other kinds of publication
- Required fields: none
- Optional fields: author, title, howpublished, month, year, note.
- @phdthesis
- Ph.D. thesis
- Required fields: author, title, year, school.
- Optional fields: address, month, keywords, note.
- @proceedings
- The proceedings of a conference.
- Required fields: title, year.
- Optional fields: editor, volume/number, series, address, month, organization, publisher, note.
- @techreport
- Technical report from educational, commercial or standardization institution.
- Required fields: author, title, institution, year.
- Optional fields: type, number, address, month, note.
- @unpublished
- An unpublished article, book, thesis, etc.
- Required fields: author, title, note.
- Optional fields: month, year.
Not standard templates
- @patent
- @collection
- @electronic
Preserving capital letters
In the event that BibTeX has been set to not preserve all capitalization within titles, problems can occur, especially if you are referring to proper nouns, or acronyms. To tell BibTeX to keep them, use the good ol' curly braces around the letter in question, (or letters, if it's an acronym) and all will be well! Or you can put the whole title in curly braces:
title = "{The LaTeX Companion}",
A few additional examples
Below you will find a few additional examples of bibliography entries. The first one covers the case of multiple authors in the Surname, Firstname format, and the second one deals with the incollection case.
@article{AbedonHymanThomas2003, author = "Abedon, S. T. and Hyman, P. and Thomas, C.", year = "2003", title = "Experimental examination of bacteriophage latent-period evolution as a response to bacterial availability", journal = "Applied and Environmental Microbiology", volume = "69", pages = "7499--7506" } @incollection{Abedon1994, author = "Abedon, S. T.", title = "Lysis and the interaction between free phages and infected cells", pages = "397--405", booktitle = "Molecular biology of bacteriophage T4", editor = "Karam, Jim D. Karam and Drake, John W. and Kreuzer, Kenneth N. and Mosig, Gisela and Hall, Dwight and Eiserling, Frederick A. and Black, Lindsay W. and Kutter, Elizabeth and Carlson, Karin and Miller, Eric S. and Spicer, Eleanor", publisher = "ASM Press, Washington DC", year = "1994" }
If you have to cite a website you can use @misc:
@MISC{website:fermentas-lambda, AUTHOR = "Fermentas Inc.", TITLE = "Phage Lambda: description \& restriction map", MONTH = "November", YEAR = 2008, HOWPUBLISHED = "\url{http://www.fermentas.com/techinfo/nucleicacids/maplambda.htm}" }
Getting current LaTeX document to use your .bib file
Actually this is not very difficult. At the end of your LaTeX file (that is, after the content, but before \end{document}, you need to place the following commands:
\bibliographystyle{plain} \bibliography{sample1,sample2,...,samplen} % Note the lack of whitespace between the commas and the next bib file.
Bibliography styles are files recognized by BibTeX that tell it how to format the information stored in the .bib file when processed for output. And so the first command 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 when using this command, as it is assumed. Despite its name, the plain style does a pretty good job (look at the output of this tutorial to see what I mean).
The second command is the one that actually specifies the .bib file you wish to use. The ones I created for this tutorial were called sample1.bib, sample2.bib, . . ., samplen.bib, but once again, you don't include the file extension. At the moment, the .bib file is in the same directory as the LaTeX document too. However, if your .bib file was elsewhere (which makes sense if you intend to maintain a centralized database of references for all your research), you need to specify the path as well, e.g \bibliography{/some/where/sample}.
Now that LaTeX and BibTeX know where to look for the appropriate files, actually citing the references is fairly trivial. The \cite{ref_key} is the command you need, making sure that the ref_key corresponds exactly to one of the entries in the .bib file. If you wish to cite more that one reference at the same time, do the following: \cite{ref_key1, ref_key2, ..., ref_keyN}.
Why won't LaTeX generate any output?
The addition of BibTeX adds extra complexity for the processing of the source to the desired output. This is largely hidden to the user, but because of all the complexity of the referencing of citations from your source LaTeX file to the database entries in another file, you actually need multiple passes to accomplish the task. This means you have to run LaTeX a number of times, where each pass, it will perform a particular task until it has managed to resolve all the citation references. Here's what you need to type:
latex latex_source_code(doesn't require .tex extension)bibtex latex_source_code(Do NOT use .tex extension)latex latex_source_code(doesn't require .tex extension)latex latex_source_code(doesn't require .tex extension)
After the first LaTeX run, you will see errors such as:
LaTeX Warning: Citation `lamport94' on page 1 undefined on input line 21. ... LaTeX Warning: There were undefined references.
The next step is to run bibtex on that same LaTeX source (and not on the actual .bib file) to then define all the references within that document. You should see output like the following:
This is BibTeX, Version 0.99c (Web2C 7.3.1) The top-level auxiliary file: latex_source_code.aux The style file: plain.bst Database file #1: sample.bib
The third step, which is invoking LaTeX for the second time will see more errors like "LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.". Don't be alarmed, it's almost complete. As you can guess, all you have to do is follow its instructions, and run LaTeX for the third time, and the document will be output as expected, without further problems.
If you want a pdf output instead of a dvi output you can use pdflatex instead of latex as follows:
pdflatex latex_source_code(doesn't require .tex extension)bibtex latex_source_code(Do NOT use .tex extension)pdflatex latex_source_code(doesn't require .tex extension)pdflatex latex_source_code(doesn't require .tex extension
Bibliography styles
Below you can see three styles available with LaTeX:
To number the references in order of apperance, rather than alphabetical order use ieetr
\bibliographystyle{ieeetr}
Web page http://www.cs.stir.ac.uk/~kjt/software/latex/showbst.html contains more examples.
Including URLs in bibliography
As you can see, there is no field for URLs. One possibility is to include Internet addresses in howpublished field of @misc or note field of @techreport, @article,@book:
howpublished = "\url{http://www.example.com}"
Note the usage of \url command to ensure proper appearance of URLs.
Another way is to use special field url and make bibliography style recognise it.
url = "http://www.example.com"
You need to use \usepackage{url} in the first case or \usepackage{hyperref} in the second case.
Styles provided by Natbib (see below) handle this field, other styles can be modified using urlbst program. Modifications of three standard styles (plain, abbrv and alpha) are provided with urlbst.
If you need more help about URLs in bibliography, visit FAQ of UK List of TeX.
Customizing bibliography appearance
One of the main advantages of BibTeX, especially for people who write many research papers, is the ability to customize your bibliography to suit the requirements of a given publication. You will notice how different publications tend to have their own style of formatting references, to which authors must adhere if they want their manuscripts published. In fact, established journals and conference organizers often will have created their own bibliography style (.bst file) for those users of BibTeX, to do all the hard work for you.
It can achieve this because of the nature of the .bib database, where all the information about your references is stored in a structured format, but nothing about style. This is a common theme in LaTeX in general, where it tries as much as possible to keep content and presentation separate.
A bibliography style file (.bst) will tell LaTeX how to format each attribute, what order to put them in, what punctuation to use in between particular attributes etc. Unfortunately, creating such a style by hand is not a trivial task. Which is why Makebst (also known as custom-bib) is the tool we need.
Makebst can be used to automatically generate a .bst file based on your needs. It is very simple, and actually asks you a series of questions about your preferences. Once complete, it will then output the appropriate style file for you to use.
It should be installed with the LaTeX distribution (otherwise, you can download it) and it's very simple to initiate. At the command line, type:
latex makebst
LaTeX will find the relevant file and the questioning process will begin. You will have to answer quite a few (although, note that the default answers are pretty sensible), which means it would be impractical to go through an example in this tutorial. However, it is fairly straight-forward. And if you require further guidance, then there is a comprehensive manual available. I'd recommend experimenting with it and seeing what the results are when applied to a LaTeX document.
If you are using a custom built .bst file, it is important that LaTeX can find it! So, make sure it's in the same directory as the LaTeX source file, unless you are using one of the standard style files (such as plain or plainnat, that come bundled with LaTeX - these will be automatically found in the directories that they are installed. Also, make sure the name of the .bst file you want to use is reflected in the \bibliographystyle{style} command (but don't include the .bst extension!).
Localizing bibliography appearance
When writing documents in languages other than English, you may find it desirable to adapt the appearance of your bibliography to the document language. This concerns words such as editors, and, or in as well as a proper typographic layout. The babelbib package can be used here. For example, to layout the bibliography in German, add the following to the header:
\usepackage[fixlanguage]{babelbib} \selectbiblanguage{german}
Alternatively, you can layout each bibliography entry according to the language of the cited document:
\usepackage{babelbib}
The language of an entry is specified as an additional field in the BibTeX entry:
@article{mueller08,
% ...
language = {german}
}
For babelbib to take effect, a bibliography style supported by it - one of babplain, babplai3, babalpha, babunsrt, bababbrv, and bababbr3 - must be used:
\bibliographystyle{babplain} \bibliography{sample}
Getting Bibliographic data
Many online databases provide bibliographic data in BibTeX-Format, making it easy to build your own database. For example, Google Scholar offers the option to return properly formatted output, but you must turn it on in the Preferences.
One should be alert to the fact that bibliographic databases are frequently the product of several generations of automatic processing, and so the resulting BibTex code is prone to a variety of minor errors, especially in older entries.
Helpful Tools
- Mendeley Mendeley is free academic software for managing PDFs which can manage a bibliography in Open Office and read BibTeX.
- Zotero Zotero is a reference manager working as a firefox plugin capable of importing and exporting bib files.
- Referencer Referencer is a Gnome application to organise documents or references, and ultimately generate a BibTeX bibliography file.
- Citavi Commercial software (with size-limited free demo version) which even searches libraries for citations and keeps all your knowledge in a database. Export of the database to all kinds of formats is possible. Works together with MS Word and Open Office Writer. Moreover plug ins for browsers and Acrobat Reader exist to automatically include references to your project.
- JabRef is a small Java program which lets you edit your BibTeX and other bibliographic databases easily, letting you (mostly) forget about the details.
- bibliographer Bibliographer is a BibTeX bibliography database editor which aims to be easy to use. Its features include linking files to your records with indexing and searching support. The interface is designed for the easy navigation of your bibliography, and double clicking a record will open the linked file.
- cb2Bib The cb2Bib is a tool for rapidly extracting unformatted, or unstandardized biblographic references from email alerts, journal Web pages, and PDF files.
- KBibTeX KBibTeX is a BibTeX editor for KDE to edit bibliographies used with LaTeX. Features include comfortable input masks, starting web queries (e. g. Google or PubMed) and exporting to PDF, PostScript, RTF and XML/HTML. As KBibTeX is using KDE's KParts technology, KBibTeX can be embedded into Kile or Konqueror.
- KBib Another BibTeX editor for KDE. It has similar capabilities, and slightly different UI. Features include BibTeX reference generation from PDF files, plain text, DOI, arXiv & PubMed IDs. Web queries to Google Scholar, PubMer, arXiv and a number of other services are also supported.
- Bibwiki Bibwiki is a Specialpage for MediaWiki to manage BibTeX bibliographies. It offers a straightforward way to import and export bibliographic records.
- BibDesk BibDesk is a bibliographic reference manager for Mac OS X. It features a very usable user interface and provides a number of features like smart folders based on keywords and live tex display.
- CiteULike CiteULike is a free online service to organise academic papers. It can export citations in BibTeX format, and can "scrape" BibTeX data from many popular websites.
- Bibtex Bibtex is a DokuWiki plugin that allows for the inclusion of bibtex formatted citations in DokuWiki pages and displays them in APA format.
- BibSonomy — A free social bookmark and publication management system based on BibTeX.
- Synapsen — Hypertextual Card Index / Reference Manager with special support for BiBTeX / biblatex, written in Java.
Summary
Although it can take a little time to get to grips with BibTeX, in the long term, it's an efficient way to handle your references. It's not uncommon to find .bib files on websites that people compile as a list of their own publications, or a survey of relevant works within a given topic, etc. Or in those huge, online bibliography databases, you often find BibTeX versions of publications, so it's a quick cut-and-paste into your own .bib file, and then no more hassle!
Having all your references in one place can be a big advantage. And having them in a structured form, that allows customizable output is another one. There are a variety of free utilities that can load your .bib files, and allow you to view them in a more efficient manner, as well as sort them and check for errors.
Bibliography in the table of contents
If you are writing a book or report, you'll likely insert your bibliography using something like:
\begin{thebibliography}{99} \bibitem{bib:one_book} some information \bibitem{bib:one_article} other information \end{thebibliography}
This will create a chapter-like output showing properly all your references. Even though it looks like a chapter, it will not be handled like that so it will not appear on the Table of Contents at the beginning of the document. If you want your bibliography to be in the table of contents, just add the following two lines just before the thebibliography environment:
\clearpage \addcontentsline{toc}{chapter}{Bibliography}
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 the Table of Contents (first option, toc), it will be like the ones created by chapters (second option, chapter), and the third argument will be printed on the corresponding line in the Table of Contents; here Bibliography was chosen because it's the same text the thebibliography environment will automatically write when you use it, but you are free to write whatever you like.
If you use hyperref package, you should also use \phantomsection command to enable hyperlinking from the table of contents to bibliography.
\clearpage \phantomsection \addcontentsline{toc}{chapter}{Bibliography}
This trick is particularly useful when you have to insert the bibliography in the Table of Contents, but it can work for anything. When LaTeX finds the code above, it will record the info as described and the current page number, inserting a new line in the Contents page.
Add the Bibliography to the Table of Contents as numbered item
If you instead want bibliography to be numbered section or chapter, you'll likely use this way:
\clearpage \section{Bibliography} \renewcommand*{\refname}{} \begin{thebibliography}{99}
This will define heading of bibliography to be empty, so you can start normal section before bibliography.
Another even easier solution is to use section inside of the renewcommand block:
\renewcommand{\refname}{\section{Sources}} \begin{thebibliography}{9} ... \end{thebibliography}
You may wish to use \renewcommand*{\refname}{\vspace*{-12mm}} to counteract the extra space the blank refname inserts.
Natbib
Using the standard LaTeX bibliography support, you will see that each reference is numbered and each citation corresponds 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 Harvard is preferred, and is in fact becoming increasingly common within scientific publications. 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 LaTeX's own citation commands, as Natbib allows the user to easily switch between Harvard or numeric.
The first job is to add the following to your preamble in order to get LaTeX to use the Natbib package:
\usepackage{natbib}
| Citation command | Output |
|---|---|
| \citet{goossens93} | Goossens et al. (1993) |
| \citep{goossens93} | (Goossens et al., 1993) |
| \citet*{goossens93} | Goossens, Mittlebach, and Samarin (1993) |
| \citep*{goossens93} | (Goossens, Mittlebach, and Samarin, 1993) |
| \citeauthor{goossens93} | Goossens et al. |
| \citeauthor*{goossens93} | Goossens, Mittlebach, and Samarin |
| \citeyear{goossens93} | 1993 |
| \citeyearpar{goossens93} | (1993) |
Also, you need to change the bibliography style file to be used, so edit the appropriate line at the bottom of the file so that it reads: \bibliographystyle{plainnat}. Once done, it is basically a matter of altering the existing \cite commands to display the type of citation you want.
The main commands simply add a t for 'textual' or p for 'parenthesized', to the basic \cite command. You will also notice how Natbib by default will compress references with three or more authors to the more concise 1st surname et al version. By adding an asterisk (*), you can override this default and list all authors associated with that citation. There are some other less common commands that Natbib supports, listed in the table here.
The final area that I wish to cover about Natbib is customizing its citation style. There is a command called \bibpunct that can be used to override the defaults and change certain settings. For example, I have put the following in the preamble:
\bibpunct{(}{)}{;}{a}{,}{,}
The command requires six mandatory parameters.
| Style | Source | Description |
|---|---|---|
| plainnat | Provided | natbib-compatible version of plain |
| abbrvnat | Provided | natbib-compatible version of abbrv |
| unsrtnat | Provided | natbib-compatible version of unsrt |
| apsrev | REVTeX 4 home page | natbib-compatible style for Physical Review journals |
| rmpaps | REVTeX 4 home page | natbib-compatible style for Review of Modern Physics journals |
| IEEEtranN | TeX Catalogue entry | natbib-compatible style for IEEE publications |
| achemso | TeX Catalogue entry | natbib-compatible style for American Chemical Society journals |
| rsc | TeX Catalogue entry | natbib-compatible style for Royal Society of Chemistry journals |
- The symbol for the opening bracket.
- The symbol for the closing bracket.
- The symbol that appears between multiple citations.
- This argument takes a letter:
- n - numerical style.
- s - numerical superscript style.
- any other letter - author-year style.
- The punctuation to appear between the author and the year (in parenthetical case only).
- The punctuation used between years, in multiple citations when there is a common author. e.g., (Chomsky 1956, 1957). If you want an extra space, then you need
{,~}.
So as you can see, this package is quite flexible, especially as you can easily switch between different citation styles by changing a single parameter. Do have a look at the Natbib manual, it's a short document and you can learn even more about how to use it.
Tables
In academic writing, tables are a common feature, often for summarising results from research. It is therefore a skill that needs mastering in order to produce good quality papers.
However, if there is one area about LaTeX that I feel is the least intuitive, then I am afraid that this is it. Basic tables are not too taxing, but you will quickly notice that anything more advanced can take a fair bit of construction. So, we will start slowly and build up from there.
The tabular environment
The tabular environment can be used to typeset tables with optional horizontal and vertical lines. LaTeX determines the width of the columns automatically.
The first line of the environment has the form:
\begin{tabular}[pos]{table spec}
the table spec argument tells LaTeX the alignment to be used in each column and the vertical lines to insert.
The number of columns does not need to be specified as it is inferred by looking at the number of arguments provided. It is also possible to add vertical lines between the columns here. The following symbols are available to describe the table columns (some of them require that the package array has been loaded):
| l | left-justified column |
| c | centered column |
| r | right-justified column |
| p{width} | paragraph column with text vertically aligned at the top |
| m{width} | paragraph column with text vertically aligned in the middle (requires array package) |
| b{width} | paragraph column with text vertically aligned at the bottom (requires array package) |
| | | vertical line |
| || | double vertical line |
By default, if the text in a column is too wide for the page, LaTeX won’t automatically wrap it. Using p{width} you can define a special type of column which will wrap-around the text as in a normal paragraph. You can pass the width using any unit supported by LaTeX, such as pt and cm, or command lengths, such as \textwidth.You can find a complete list in appendix Useful Measurement Macros.
The optional parameter pos can be used to specify the vertical position of the table relative to the baseline of the surrounding text. You can use the following letters:
| h | here |
| b | bottom |
| c | center |
| t | top |
LaTeX will take your preferences into account when placing the table. For example, when you mention the preferred position pos as [htb], LaTeX will try to place the table here first, if that does not work out, it will place the table at the top of a page, and if that does not work out, it uses the bottom position.
In the first line you have pointed out how many columns you want, their alignment and the vertical lines to separate them. Once in the environment, you have to introduce the text you want, separating between cells and introducing new lines. The commands you have to use are the following:
| & | column separator |
| \\ | start new row (additional space may be specified after \\ using square brackets, such as \\[6pt]) |
| \hline | horizontal line |
| \cline{i-j} | partial horizontal line beginning in column i and ending in column j |
Note, any white space inserted between these commands is purely down to ones' preferences. I personally add spaces between to make it easier to read.
Basic examples
This example shows how to create a simple table in LaTeX. It is a three-by-three table, but without any lines.
\begin{tabular}{ l c r } 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{tabular} |
Expanding upon that by including some vertical lines:
\begin{tabular}{ l | c || r | } 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{tabular} |
To add horizontal lines to the very top and bottom edges of the table:
\begin{tabular}{ l | c || r | } \hline 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \hline \end{tabular} |
And finally, to add lines between all rows, as well as centering (notice the use of the center environment - of course, the result of this is not obvious from the preview on this web page):
\begin{center} \begin{tabular}{ l | c || r | } \hline 1 & 2 & 3 \\ \hline 4 & 5 & 6 \\ \hline 7 & 8 & 9 \\ \hline \end{tabular} \end{center} |
\begin{tabular}{|r|l|} \hline 7C0 & hexadecimal \\ 3700 & octal \\ \cline{2-2} 11111000000 & binary \\ \hline \hline 1984 & decimal \\ \hline \end{tabular} |
Column specification using >{\cmd} and <{\cmd}
Using the array package, one is able to alter the column specification. This is done in the argument of the tabular environment using >{\command} for commands executed right before each column element. The code <{\command} for commands to be executed right after each column element. As an example: to get a column in math mode enter: \begin{tabular}{>{$}c<{$}}. Another example is changing the font: \begin{tabular}{>{\small}c} to print the column in a small font.
The argument of the > and < specifications must be correctly balanced when it comes to { and } characters. This means that >{\bfseries} is valid, while >{\textbf} will not work and >{\textbf{} is not valid. If there is the need to use the text of the table as an argument (for instance, using the \underline to produce a line below the text), one should use the \bgroup and \egroup commands: >{\underline\bgroup}c<{\egroup} produces the intended effect.
Text wrapping in tables
LaTeX's algorithms for formatting tables have a few shortcomings. One is that it will not automatically wrap text in cells, even if it has overrun the width of the page. For columns that you know will contain a certain amount of text, then it is recommended that you use the p attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). Use the m attribute to have the lines aligned toward the middle of the box and the b attribute to align along the bottom of the box.
Here is a practical example. The following code creates two tables with the same code; the only difference is that the last column of the second one has a defined width of 5 centimeters, while in the first one we didn't specify any width. Compiling this code:
\documentclass{article} \usepackage[english]{babel} \begin{document} Without specifying width for last column: \begin{center} \begin{tabular}{ | l | l | l | l |} \hline Day & Min Temp & Max Temp & Summary \\ \hline Monday & 11C & 22C & A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. \\ \hline Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest. \\ \hline Wednesday & 10C & 21C & Rain will still linger for the morning. Conditions will improve by early afternoon and continue throughout the evening. \\ \hline \end{tabular} \end{center} With width specified: \begin{center} \begin{tabular}{ | l | l | l | p{5cm} |} \hline Day & Min Temp & Max Temp & Summary \\ \hline Monday & 11C & 22C & A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures. \\ \hline Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells across most of Scotland and Northern Ireland, but rain reaching the far northwest. \\ \hline Wednesday & 10C & 21C & Rain will still linger for the morning. Conditions will improve by early afternoon and continue throughout the evening. \\ \hline \end{tabular} \end{center} \end{document}
You get the following output:
Note that the first table is cropped: The output is wider than the page width.
Other environments inside tables
If you use some LaTeX enviroments inside table cells, like verbatim or enumerate
\begin{tabular}{| c | c |} \hline \begin{verbatim} code \end{verbatim} & description \\ \hline \end{tabular}
you might encounter errors similar to
! LaTeX Error: Something's wrong--perhaps a missing \item.
To solve this problem, change column specifier to "paragraph" (p, m or b).
\begin{tabular}{| m{5cm} | c |}
Defining multiple columns
It is possible to define many identical columns at once using the *{num}{str} syntax.
This is particularly useful when your table has many columns.
Here is a table with six centered columns flanked by a single column on each side:
\begin{tabular}{l*{6}{c}r} Team & P & W & D & L & F & A & Pts \\ \hline Manchester United & 6 & 4 & 0 & 2 & 10 & 5 & 12 \\ Celtic & 6 & 3 & 0 & 3 & 8 & 9 & 9 \\ Benfica & 6 & 2 & 1 & 3 & 7 & 8 & 7 \\ FC Copenhagen & 6 & 2 & 1 & 2 & 5 & 8 & 7 \\ \end{tabular} |
@-expressions
The column separator can be specified with the @{...} construct.
It typically takes some text as its argument, and when appended 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 replaces it with whatever is between the curly braces. To add space, use @{\hspace{width}}.
Admittedly, this is not that clear, and so will require a few examples to clarify. Sometimes, it is desirable in scientific tables to have the numbers aligned on the decimal point. This can be achieved by doing the following:
\begin{tabular}{r@{.}l} 3 & 14159 \\ 16 & 2 \\ 123 & 456 \\ \end{tabular} |
Note that the approach outlined above won't work well if the column header is longer than any of the numbers. To center the column on the decimal separator, use the dcolumn package, which provides a new column specifier for floating point data.
The space suppressing qualities of the @-expression actually make it quite useful for manipulating the horizontal spacing between columns. Given a basic table, and varying the column descriptions:
\begin{tabular}{|l|l|} \hline stuff & stuff \\ \hline stuff & stuff \\ \hline \end{tabular}
| {|l|l|} | |
| {|@{}l|l@{}|} | |
| {|@{}l@{}|l@{}|} | |
| {|@{}l@{}|@{}l@{}|} |
Spanning
To complete this tutorial, we take a quick look at how to generate slightly more complex tables. Unsurprisingly, the commands necessary have to be embedded within the table data itself.
Rows spanning multiple columns
The command for this looks like this: \multicolumn{num_cols}{alignment}{contents}. num_cols is the number of subsequent columns to merge; alignment is, either l, c, r or to have text wrapping specifiy a width p{5.0cm} . And contents is simply the actual data you want to be contained within that cell. A simple example:
\begin{tabular}{|l|l|} \hline \multicolumn{2}{|c|}{Team sheet} \\ \hline GK & Paul Robinson \\ LB & Lucus Radebe \\ DC & Michael Duberry \\ DC & Dominic Matteo \\ RB & Didier Domi \\ MC & David Batty \\ MC & Eirik Bakke \\ MC & Jody Morris \\ FW & Jamie McMaster \\ ST & Alan Smith \\ ST & Mark Viduka \\ \hline \end{tabular} |
Columns spanning multiple rows
The first thing you need to do is add \usepackage{multirow} to the preamble. This then provides the command needed for spanning rows: \multirow{num_rows}{width}{contents}. The arguments are pretty simple to deduce (* for the width means the contents natural width).
... \usepackage{multirow} ... \begin{tabular}{|l|l|l|} \hline \multicolumn{3}{|c|}{Team sheet} \\ \hline Goalkeeper & GK & Paul Robinson \\ \hline \multirow{4}{*}{Defenders} & LB & Lucus Radebe \\ & DC & Michael Duberry \\ & DC & Dominic Matteo \\ & RB & Didier Domi \\ \hline \multirow{3}{*}{Midfielders} & MC & David Batty \\ & MC & Eirik Bakke \\ & MC & Jody Morris \\ \hline Forward & FW & Jamie McMaster \\ \hline \multirow{2}{*}{Strikers} & ST & Alan Smith \\ & ST & Mark Viduka \\ \hline \end{tabular} |
The main thing to note when using \multirow is that a blank entry must be inserted for each appropriate cell in each subsequent row to be spanned.
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 a table of n columns, there must always be n - 1 ampersands in each row. The exception to this is when \multicolumn and \multirow are used to create cells which span multiple columns or rows.
Spanning in both directions simultaneously
Here is a nontrivial example how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:
\usepackage{multirow} \begin{tabular}{cc|c|c|c|c|l} \cline{3-6} & & \multicolumn{4}{|c|}{Primes} \\ \cline{3-6} & & 2 & 3 & 5 & 7 \\ \cline{1-6} \multicolumn{1}{|c|}{\multirow{2}{*}{Powers}} & \multicolumn{1}{|c|}{504} & 3 & 2 & 0 & 1 & \\ \cline{2-6} \multicolumn{1}{|c|}{} & \multicolumn{1}{|c|}{540} & 2 & 3 & 1 & 0 & \\ \cline{1-6} \multicolumn{1}{|c|}{\multirow{2}{*}{Powers}} & \multicolumn{1}{|c|}{gcd} & 2 & 2 & 0 & 0 & min \\ \cline{2-6} \multicolumn{1}{|c|}{} & \multicolumn{1}{|c|}{lcm} & 3 & 3 & 1 & 1 & max \\ \cline{1-6} \end{tabular} |
The dummy command \multicolumn{1}{|c|}{...} is just used to draw vertical borders both on the left and on the right of the cell. Even when combined with \multirow{2}{*}{...}, it still draws vertical borders that only span the first row. To compensate for that, we add \multicolumn{1}{|c|}{} in the following rows spanned by the multirow. Note that we cannot just use \hline to draw horizontal lines, since we do not want the line to be drawn over the text that spans several rows. Instead we use the command \cline{2-6} and opt out the first column that contains the text "Powers".
Resize tables
The command \resizebox{width}{height}{object} can be used with tabular to specify the height and width of a table. The following example shows how to resize a table to 8cm width while maintaining the original width/height ratio.
\resizebox{8cm}{!} { \begin{tabular}... \end{tabular} }
Alternatively you can use \scalebox{ratio}{object} in the same way but with ratios rather than fixed sizes:
\scalebox{0.7}{ \begin{tabular}... \end{tabular} }
To tweak the space between columns (LaTeX will by default chose very tight columns), one can alter the column separation: \setlength{\tabcolsep}{5pt}. The default value is 6pt.
Sideways tables
Tables can also be put on their side within a document using the rotating package and the sidewaystable environments in place of the table environment. (NOTE: most DVI viewers do not support displaying rotated text. Convert your document to a PDF to see the result. Most, if not all, PDF viewers do support rotated text.)
\usepackage{rotating} \begin{sidewaystable} \begin{tabular}... \end{tabular} \end{sidewaystable}
When it is desirable to place the rotated table at the exact location where it appears in the source (.tex) file, rotfloat package may be used. Then one can use \begin{sidewaystable}[H] just like for normal tables. The 'H' option can not be used without this package.
Alternate Row Colors in Tables
The xcolor package provides the necessary commands to produce tables with alternate row colors, when loaded with the table option. The command \rowcolors{<starting row>}{<odd color>}{<even color>} has to be specified right before the tabular environment starts.
\documentclass{article} \usepackage[table]{xcolor} \begin{document} \begin{center} \rowcolors{1}{green}{pink} \begin{tabular}{lll} odd & odd & odd \\ even & even & even\\ odd & odd & odd \\ even & even & even\\ \end{tabular} \end{center} \end{document}
The command \hiderowcolors is available to deactivate highlighting of a specified row. Highlighting can be reactivated within the table via the \showrowcolors command.
Colors of individual Cells
As above this uses the xcolor package.
% Include this somewhere in your document \usepackage[table]{xcolor} % Enter this in the cell you wish to color a light grey. % NB: the word 'grey' here denotes the grayscale color scheme, not the color grey. `0.9' denotes how dark the Grey is. \cellcolor[gray]{0.9} % The following will color the cell red. \cellcolor{red}
The table environment - captioning etc
Although the tabular environment typesets tables brilliantly, it doesn't cover all that you need to do with tables. For example, you might want a caption for your table. For this and other reasons, you should typically place your tabular environment inside a table environment:
\begin{table} \caption{Performance at peak F-measure} \begin{tabular}{| r | r || c | c | c |} ... \end{tabular} \end{table}
Why do the two different environments exist? Think of it this way: The tabular environment is concerned with arranging elements in a tabular grid, while the table environment represents the table more conceptually. This explains why it isn't tabular but table that provides for captioning (because the caption isn't displayed in the grid-like layout).
A table environment has a lot of similarities with a figure environment, in the way the "floating" is handled etc. For instance you can specify its placement in the page with the option [placement], the valid values are any combination of (order is not important):
| h | where the table is declared (here) |
| t | at the top of the page |
| b | at the bottom of the page |
| p | on a dedicated page of floats |
| ! | override the default float restrictions. E.g., the maximum size allowed of a b float is normally quite small; if you want a large one, you need this ! parameter as well. |
The default is [tbp]. If you want to place a table in the place where it's declared, do not just write [h]; if the table cannot fit (because the text is near the bottom of the page, say) it will float to a dedicated page of floats (as if it were a p float) which can be some distance away in the document. A good rule of thumb is to always use htbp until the document is finished, at which stage the final float parameters can be fine-tuned.
The table environment is also useful when you want to have a list of tables at the beginning or end of your document with the command \listoftables; it enables making cross-references to the table with:
You may refer to table~\ref{my_table} for an example. ... \begin{table} \begin{tabular} ... \end{tabular} \caption{An example of table} \label{my_table} \end{table}
The tabular* environment - controlling table width
This is basically a slight extension on the original tabular version, although it requires an extra argument (before the column descriptions) to specify the preferred width of the table.
\begin{tabular*}{0.75\textwidth}{ | c | c | c | r | } \hline label 1 & label 2 & label 3 & label 4 \\ \hline item 1 & item 2 & item 3 & item 4 \\ \hline \end{tabular*} |
However, that doesn't look quite as intended. The columns are still at their natural width (just wide enough to fit their contents) whilst the rows are as wide as the table width specified. This looks very ugly. The reason for the mess is that you must also explicitly insert extra column space. Fortunately, LaTeX has rubber lengths, which unlike others, are not fixed, and LaTeX can dynamically decide how long they should be. So, the solution to the current problem is:
\begin{tabular*}{0.75\textwidth}{@{\extracolsep{\fill}} | c | c | c | r | } \hline label 1 & label 2 & label 3 & label 4 \\ \hline item 1 & item 2 & item 3 & item 4 \\ \hline \end{tabular*}
You will notice the @{...} construct added at the beginning of the column description. Within it is the \extracolsep command, which requires a width. A fixed width could have been used, however, by using a rubber length, such as \fill, the columns are automatically spaced evenly.
The tabularx package - simple column stretching
This package provides a table environment called tabularx which is similar to the tabular* environment, except that it has a new column specifier X (in uppercase). The column(s) specified with this specifier will be stretched to make the table as wide as specified, greatly simplifying the creation of tables.
\usepackage{tabularx} ... \begin{tabularx}{\textwidth}{ |X|X|X|X| } \hline label 1 & label 2 & label 3 & label 4 \\ \hline item 1 & item 2 & item 3 & item 4 \\ \hline \end{tabularx} |
The content provided for the boxes is treated as for a p column, except that the width is calculated automatically. If you use the package array, you may also apply any >{\cmd} or <{\cmd} command to achieve specific behavior (like \centering, or \raggedright\arraybackslash) as described previously.
Another option is the use of \newcolumntype in order to get selected columns formatted in a different way. It defines a new column specifier, e.g. R (in uppercase). In this example, the second and fourth column is adjusted in a different way (\raggedleft):
\usepackage{tabularx} ... \newcolumntype{R}{>{\raggedleft\arraybackslash}X}% \begin{tabularx}{\textwidth}{ |l|R|l|R| } \hline label 1 & label 2 & label 3 & label 4 \\ \hline item 1 & item 2 & item 3 & item 4 \\ \hline \end{tabularx} |
Vertically centered images
Inserting images into a table row will align it at the top of the cell. By using the array package this problem can be solved. Defining a new columntype will keep the image vertically centered.
\newcolumntype{V}{>{\centering\arraybackslash} m{.4\linewidth} } |
Or use a parbox to center the image.
\parbox[c]{1em}{\includegraphics{image.png}} |
Professional tables
Many tables in professionally typeset books and journals feature simple tables, which have appropriate spacing above and below lines, and almost never use vertical rules. Many examples of LaTeX tables (including this Wikibook) showcase the use of vertical rules (using "|"), and double-rules (using \hline\hline" or "||"), which are regarded as unnecessary and distracting in a professionally published form. The booktabs package is useful for easily providing this professionalism in LaTeX tables, and the documentation also provides guidelines on what constitutes a "good" table.
In brief, the package uses \toprule for the uppermost rule (or line), \midrule for the rules appearing in the middle of the table (such as under the header), and \bottomrule for the lowermost rule. This ensures that the rule weight and spacing are acceptable. In addition, \cmidrule can be used for mid-rules that span specified columns. The following example contrasts the use of booktabs and normal LaTeX implementations (the later example requires \usepackage{booktabs} in the preamble).
Tables with different font size
A table can be globally switched to a different font size by simply adding the desired size command (here: \footnotesize) after the \begin{table}... statement:
\begin{table}[h]\footnotesize \caption{Performance at peak F-measure} \begin{tabular}{| r | r || c | c | c |} ... \end{tabular} \end{table}
The table caption font size is not affected.
To control the caption font size, see Caption Styles.
Need more complicated features?
Have a look at one of the following packages:
- hhline: do whatever you want with horizontal lines
- array: gives you more freedom on how to define columns
- colortbl: make your table more colorful
- supertab: for tables that need to stretch over several pages
- longtable: same as above. Note: footnotes do not work properly in a normal tabular environment. If you replace it with a longtable environment, footnotes work properly
- xtabular: Yet another package for tables that need to span many pages
- tabulary: modified tabular* allowing width of columns set for equal heights
Summary
This concludes discussion of basic tables. Experimentation quickly leads to mastery. The table syntax in LaTeX can look rather messy, and seeing new examples can look confusing. But hopefully, enough has been covered here so that a user can create any table needed for your papers. Unsurprisingly, LaTeX has plenty more up its sleeve, so expect a follow up tutorial covering more advanced features in the near future.
Formatting
The term formatting is rather broad, but in this case it needs to be as this section will guide you through the various text, paragraph and page formatting techniques. Formatting tends to refer to most things to do with appearance, it makes the list of possible topics quite eclectic: text style, font, size; paragraph alignment, interline spacing, indents; special paragraph types; list structures; footnotes, margin notes, etc.
A lot of the formatting techniques are required to differentiate certain elements from the rest of the text. It is often necessary to add emphasis to key words or phrases. A numbered or bulleted list is also commonly used as a clear and concise way of communicating an important issue. Footnotes are useful for providing extra information or clarification without interrupting the main flow of text. So, for these reasons, formatting is very important. However, it is also very easy to abuse, and a document that has been over-done can look and read worse than one with none at all.
Text formatting
Hyphenation
LaTeX hyphenates words whenever necessary. If the hyphenation algorithm does not find the correct hyphenation points, you can remedy the situation by using the following commands to tell TeX about the exception. The command
\hyphenation{word list}
causes the words listed in the argument to be hyphenated only at the points marked by “-”. The argument of the command should only contain words built from normal letters, or rather characters that are considered to be normal letters by LaTeX. The hyphenation hints are stored for the language that 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 language hyphenation. If you place the command after the \begin{document} and you are using some package for national language support like babel, then the hyphenation hints will be active in the language activated through babel. The example below will allow “hyphenation” to be hyphenated as well as “Hyphenation”, and it prevents “FORTRAN”, “Fortran” and “fortran” from being hyphenated at all. No special characters or symbols are allowed in the argument. Example:
\hyphenation{FORTRAN Hy-phen-a-tion}
The command \- inserts a discretionary hyphen into a word. This also becomes the only point hyphenation is allowed in this word. This command is especially useful for words containing special characters (e.g., accented characters), because LaTeX does not automatically hyphenate words containing special characters.
\begin{minipage}{2in} I think this is: su\-per\-cal\-% i\-frag\-i\-lis\-tic\-ex\-pi\-% al\-i\-do\-cious \end{minipage} |
![]() |
Several words can be kept together on one line with the command
\mbox{text}
It causes its argument to be kept together under all circumstances. Example:
My phone number will change soon. It will be \mbox{0116 291 2319}.
\fbox is similar to \mbox, but in addition there will be a visible box drawn around the content.
To avoid hyphenation altogether, the penalty for hyphenation can be set to an extreme value:
\hyphenpenalty=100000
Quotes
Latex treats left and right quotes as different entities. For single quotes, ` (on British and American keyboards, this symbol is found on the key adjacent to the number 1) gives a left quote mark, and ' is the right. For double quotes, simply double the symbols, and Latex will interpret them accordingly. (Although, you can use the " for right double quotes if you wish).
| To `quote' in Latex | |
| To ``quote'' in Latex | |
| To ``quote" in Latex | |
| ``Please press the ‘x' key.'' | “Please press the ‘x’ key.” |
The right quote is also used for apostrophe in Latex without trouble.
Diacritics
It does not take long before you need to use an accented character within your document. Personally, I find it tends to be names of researchers whom I wish to cite which contain diacritics. It's easy to apply, although not all are easy to remember:
To place a diacritic on top of an i or a j, its dot has to be removed. This is accomplished by typing \i and \j. If you have to write all your document in a foreign language and you have to use particular diacritics several times, then using the right configuration you can write those characters directly in your document. For more information, see the section Internationalization.
The Space Between Words
To get a straight right margin in the output, LaTeX inserts varying amounts of space between the words. It inserts slightly more space at the end of a sentence, as this makes the text more readable. LaTeX assumes that sentences end with periods, question marks or exclamation marks. If a period follows an uppercase letter, this is not taken as a sentence ending, since periods after uppercase letters normally occur in abbreviations.
Any exception from these assumptions has to be specified by the author. A backslash in front of a space generates a space that will not be enlarged. A tilde ‘~’ character generates a space that cannot be enlarged and additionally prohibits a line break. The command \@ in front of a period specifies that this period terminates a sentence even when it follows an uppercase letter.
The additional space after periods can be disabled with the command
\frenchspacing
which tells LaTeX not to insert more space after a period than after ordinary character. This is very common in non-English languages, except bibliographies. If you use \frenchspacing, the command \@ is not necessary.
Some very long words, numbers or URLs may not be hyphenated properly and move far beyond side margin. One solution for this problem is to use sloppypar environment, which tells LaTeX to adjust word spacing less strictly. As result, some spaces between words may be a bit too large, but long words will be placed properly.
Ligatures
Some letter combinations are typeset not just by setting the different letters one after the other, but by actually using special symbols (like "ff"), called ligatures. Ligatures can be prohibited by inserting {} or, if this does not work, {\kern0pt} between the two letters in question. This might be necessary with words built from two words. Here is an example:
\Large Not shelfful\\ but shelf{}ful |
Slash marks
The normal typesetting of the / character in LaTeX does not allow following characters to be "broken" on to new lines, which often create "overfull" errors in output (where letters push off the margin). Words that use slash marks, such as "input/output" should be typeset as "input\slash output", which allow the line to "break" after the slash mark (if needed). The use of the / character in LaTeX should be restricted to units, such as "mm/year", which should not be broken over multiple lines.
Emphasizing Text
In order to add some emphasis to a word or phrase, the simplest way is to use the \emph{text} command. That's it! See, dead easy.
I want to \emph{emphasize} a word. |
Font Styles and size
I will really only scratch the surface about this particular field. This section is not about how to get your text in Verdana size 12pt! There are three main font families: roman (such as Times), sans serif (eg Arial) and monospace (eg Courier). You can also specify styles such as italic and bold:
The following table lists the commands you will need to access the typical font styles:
| LaTeX command | Equivalent to | Output style | Remarks |
|---|---|---|---|
\textnormal{…} |
{\normalfont …} |
document font family | this is the default or normal font |
\emph{…} |
{\em …} |
emphasis | typically italics |
\textrm{…} |
{\rmfamily …} |
roman font family | |
\textsf{…} |
{\sffamily …} |
sans serif font family | |
\texttt{…} |
{\ttfamily …} |
teletypefont family | this is a fixed-width or monospace font |
\textup{…} |
{\upshape …} |
upright shape | the same as the normal typeface |
\textit{…} |
{\itshape …} |
italic shape | |
\textsl{…} |
{\slshape …} |
slanted shape | a skewed version of the normal typeface (similar, but slightly different than italics) |
\textsc{…} |
{\scshape …} |
Small Capitals | |
\textbf{…} |
{\bfseries …} |
bold | |
\textmd{…} |
{\mdseries …} |
medium weight | a font weight in between normal and bold |
You may have noticed the absence of underline. Although this is available via the \underline{...} command, text underlined in this way will not break properly. This functionality has to be added with the ulem package. Stick \usepackage{ulem} in your preamble. By default, this overrides the \emph command with the underline rather than the italic style. It is unlikely that you wish this to be the desired effect, so it is better to stop ulem taking over \emph and simply call the underline command as and when it is needed.
- To disable
ulem, add\normalemstraight after the document environment begins. - To underline, use
\uline{...}. - To add a wavy underline, use
\uwave{...}. - And for a strike-out
\sout{...}.
Finally, there is the issue of size. This too is very easy, simply follow the commands on this table:
|
Note that the font size definitions are set by the document style. Depending on the document style the actual font size may differ from that listed above. And not every document style has unique sizes for all 10 size commands.
Even if you can easily change the output of your fonts using those commands, you're better off not using explicit commands like this, because they work in opposition to the basic idea of LaTeX, which is to separate the logical and visual markup of your document. This means that if you use the same font changing command in several places in order to typeset a special kind of information, you should use \newcommand to define a "logical wrapper command" for the font changing command.
\newcommand{\oops}[1]{\textbf{#1}} Do not \oops{enter} this room, it’s occupied by \oops{machines} of unknown origin and purpose. |
Do not enter this room, it’s occupied by machines of unknown origin and purpose. |
This approach has the advantage that you can decide at some later stage that you want to use some visual representation of danger other than \textbf, without having to wade through your document, identifying all the occurrences of \textbf and then figuring out for each one whether it was used for pointing out danger or for some other reason.
Text mode superscript and subscript
To superscript text in text-mode, you can use the \textsuperscript{} command. This allows you to, for instance, typeset 6th as 6th:
Michelangelo was born on March 6\textsuperscript{th}, 1475. |
The primary use of subscripts within the text environment is to typeset chemical formulae. For this purposes, a highly recommended package is mhchem. This package is easy to use, and works with your text fonts (rather than math fonts). To insert a chemical formula, use \ce{} with the text-equivalent formula, for example:
% In your preamble, add: \usepackage[version=3]{mhchem} ... % In your document: Ammonium sulphate is \ce{(NH4)2SO4}. |
Subscripting in text-mode is not supported by LaTeX alone, however, several packages allow the use of the \textsubscript{} command. For instance, bpchem, KOMA-Script2 and, perhaps the most universal option since it is distributed with LaTeX, fixltx2e all support this command.
% In your preamble, add: \usepackage{fixltx2e} ... % In your document: It is found that height\textsubscript{apple tree} is different than height\textsubscript{orange tree}. |
It is found that heightapple tree is different than heightorange tree. |
If you do not load a package that supports \textsubscript{}, the math mode must be used. This is easily accomplished in running text by bracketing your text with the $ symbol. In math mode subscripting is done using the underscore: _{}.
For example, the formula for water is written as:
H$_2$O is the formula for water
|
H2O is the formula for water |
Note that in math mode text will appear in a font suitable for mathematical variables. In math mode, to generate roman text, for example, one would use the \mathrm command:
This is $\mathrm{normal\ roman\ and}_\mathrm{subscript\ roman}$ text
|
This is normal roman andsubscript roman text |
Note the use of \<space> to insert a space in math mode.
Similarly, you can superscript using:
This is $\mathrm{normal\ roman\ and}^\mathrm{superscript\ roman}$ text
|
This is normal roman andsuperscript roman text |
Text figures ("old style" numerals)
Many typographers prefer to use titling figures, sometimes called lining figures, when numerals are interspersed with full caps, when they appear in tables, and when they appear in equations, using text figures elsewhere. LaTeX allows this usage through the \oldstylenums{} command:
\oldstylenums{1234567890} |
Some fonts do not have text figures built in; the textcomp package attempts to remedy this by effectively generating text figures from the currently-selected font. Put \usepackage{textcomp} in your preamble. textcomp also allows you to use decimal points, properly formatted dollar 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 placing some code in your preamble:
\usepackage{textcomp} % Enclose everything in an \AtBeginDocument{} \AtBeginDocument{% % Make \section{} use text figures \let\myTheSection\thesection \renewcommand{\thesection}{\oldstylenums{\myTheSection}} % Make \paragraph{} use text figures \let\myTheParagraph\theparagraph \renewcommand{\theparagraph}{\oldstylenums{\myTheParagraph}} % Make the page numbers in text figures \let\myThePage\thepage \renewcommand{\thepage}{\oldstylenums{\myThePage}} } |
Should you use additional sectioning or paragraphing commands, you may adapt the previous code listing to include them as well.
Symbols and special characters
Dashes and Hyphens
LaTeX knows four kinds of dashes: a hyphen (-), en dash (–), em dash (—), or a minus sign (−). You can access three of them with different numbers of consecutive dashes. The fourth sign is actually not a dash at all—it is the mathematical minus sign:
Hyphen: daughter-in-law, X-rated\\ En dash: pages 13--67\\ Em dash: yes---or no? \\ Minus sign: $0$, $1$ and $-1$ |
The names for these dashes are: ‘-’(-) hyphen , ‘--’(–) en-dash , ‘---’(—) em-dash and ‘ - ’(−) minus sign. They have different purposes:
Euro € currency symbol
When writing about money these days, you need the euro sign. You have several choices. If the fonts you are using have a euro symbol and you want to use that one, first you have to load the textcomp package in the preamble:
\usepackage{textcomp}
then you can insert the euro symbol with the command \texteuro. If you want to use the official version of the euro symbol, then you have to use eurosym, load it with the official option in the preamble:
\usepackage[official]{eurosym}
then you can insert it with the \euro command. Finally, if you want a euro symbol that matches with the current font style (e.g., bold, italics, etc.) but your current font does not provide it, you can use the eurosym package again but with a different option:
\usepackage[gen]{eurosym}
again you can insert the euro symbol with \euro
Ellipsis (…)
A sequence of three dots is known as an ellipsis, which is commonly used to indicate omitted text. On a typewriter, a comma or a period takes the same amount of space as any other letter. In book printing, these characters occupy only a little space and are set very close to the preceding letter. Therefore, you cannot enter ‘ellipsis’ by just typing three dots, as the spacing would be wrong. Instead, there is a special command for these dots. It is called \ldots:
Not like this ... but like this:\\ New York, Tokyo, Budapest, \ldots |
Ready-made strings
There are some very simple LaTeX commands for typesetting special text strings:
Other symbols
Latex has lots of symbols at its disposal. The majority of them are within the mathematical domain, and later chapters will cover how to get access to them. For the more common text symbols, use the following commands:
Not mentioned in above table, tilde (~) is used in LaTeX code to produce non-breakable space. To get printed tilde sign, either make it verbatim text or write \~{}.
Of course, these are rather boring, and it just so happens that for some more interesting symbols, then the Postscript ZipfDingbats font is available thanks to the pifont. Hopefully, you are beginning to notice now that when you want to use a package, you need to add the declaration to your preamble, in this instance: \usepackage{pifont}. Next, the command \ding{number}, will print the specified symbol. Here is a table of the available symbols:
Paragraph Formatting
Altering the paragraph formatting is not often required, especially in academic writing. However, it is useful to know, and applications tend to be for formatting text in floats, or other more exotic documents.
Paragraph Alignment
Paragraphs in Latex are usually fully justified (i.e., flush with both the left and right margins). For whatever reason, should you wish to alter the justification of a paragraph, there are three environments at hand, and also Latex command equivalents.
| Alignment | Environment | Command |
|---|---|---|
| Left justified | flushleft | \raggedright |
| Right justified | flushright | \raggedleft |
| Center | center | \centering |
All text between the \begin and \end of the specified environment will be justified appropriately. The commands listed are for use within other environments. For example, p (paragraph) columns in tabular.
Paragraph Indents
Paragraph indents are normally fine. The size of the indent is determined by a parameter called \parindent. The default length that this constant holds is set by the document class that you use. It is possible to override using the \setlength command.
\setlength{\parindent}{length}
will reset the indent to length.
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 between paragraphs is held in \parskip, which could be altered in a similar fashion as above. However, this parameter is used elsewhere too, such as in lists, which means you run the risk of making various parts of your document look very untidy (that is, even more untidy than this type of paragraph style!) It may be better to use a document class typeset for this style of indentation, such as artikel3.cls (written by a Dutch person, translates to article3).
To indent subsequent lines of a paragraph, use the TeX command \hangindent. (While the default behavior is to apply the hanging indent after the first line, this may be changed with the \hangafter command.) An example follows.
\hangindent=0.7cm This paragraph has an extra indentation at the left.
The TeX commands \leftskip and \rightskip add additional space to the left and right sides of each line, allowing the formatting for subsequent paragraphs to differ from the overall document margins. This space is in addition to the indentation added by \parindent and \hangindent.
To change the indentation of the last line in a paragraph, use the TeX command \parfillskip.
Line Spacing
To change line spacing in the whole document use the command \linespread covered in LaTeX/Customizing_LaTeX#Spacing.
To change line spacing in specific environments do the following:
- Add
\usepackage{setspace}to the document preamble. - This then provides the following environments to use within your document:
doublespace- all lines are double spaced.onehalfspace- line spacing set to one-and-half spacing.singlespace- normal line spacing.
After declaring the package in the preamble the use of the command \singlespacing, \doublespacing, or \onehalfspacing will specify the line spacing for all sections and paragraphs until another command is used.
See the section on customizing lists below for information on how to change the line spacing in lists.
Special Paragraphs
For those of you who have read most/all of the tutorials so far, you will have already come across some of the following paragraph formats. Although seen before, it makes sense to re-introduce here, for the sake of completeness.
Verbatim Text
There are several ways to introduce text that won't be interpreted by the compiler. If you use the verbatim environment, everything input between the begin and end commands are processed as if by a typewriter. All spaces and new lines are reproduced as given, and the text is displayed in an appropriate fixed-width font. Any LaTeX command will be ignored and handled as plain text. Ideal for typesetting program source code. This environment was used in an example in the previous tutorial. Here is an example:
\begin{verbatim} The verbatim environment simply reproduces every character you input, including all s p a c e s! \end{verbatim} |
Note: once in the verbatim environment, the only command that will be recognized is \end{verbatim}. Any others will be output, verbatim! If this is an issue, then you can use the alltt package instead, providing an environment with the same name:
\begin{alltt} Verbatim extended with the ability to use normal commands. Therefore, it is possible to \emph{emphasize} words in this environment, for example. \end{alltt} |
Remember to add \usepackage{alltt} to your preamble to use it though! Within the alltt environment, you can use the command \normalfont to get back the normal font.
If you just want to introduce a short verbatim phrase, you don't need to use the whole environment, but you have the \verb command:
\verb+my text+
The first character following \verb is the delimiter: here we have used "+", but you can use any character you like but * and space; \verb will print verbatim all the text after it until it finds the next delimiter. For example, the code:
\verb|\textbf{Hi mate!}|
will print \textbf{Hi mate!}, ignoring the effect \textbf should have on text.
For more control over formatting, however, you can try the fancyvrb package, which provides a Verbatim environment (note the capital letter) which lets you draw a rule round the verbatim text, change the font size, and even have typographic effects inside the Verbatim environment. It can also be used in conjunction with the fancybox package and it can add reference line numbers (useful for chunks of data or programming), and it can even include entire external files.
Typesetting URLs
One of either the hyperref or url packages provides the \url command, which properly typesets URLs, for example:
Go to \url{http://www.uni.edu/~myname/best-website-ever.html} for my website.
will show this URL exactly as typed (similar to the \verb command), but the \url command also performs a hyphenless break at punctuation characters. It was designed for Web URLs, so it understands their syntax and will never break mid-way through an unpunctuated word, only at slashes and full stops. Bear in mind, however, that spaces are forbidden in URLs, so using spaces in \url arguments will fail, as will using other non-URL-valid characters.
When using this command through the hyperref package, the URL is "clickable" in the PDF document, whereas it is not linked to the web when using only the url package. Also when using the hyperref package, to remove the border placed around a URL, insert pdfborder = {0 0 0 0} inside the \hypersetup{}.
Listing Environment
This is also an extension of the verbatim environment provided by the moreverb package. The extra functionality it provides is that it can add line numbers along side the text. The command: \begin{listing}[step]{first line}. The mandatory first line argument is for specifying which line the numbering shall commence. The optional step is the step between numbered lines (the default is 1, which means every line will be numbered).
To use this environment, remember to add \usepackage{moreverb} to the document preamble.
Multi-line comments
As we have seen, the only way LaTeX allows you to add comments is by using the special character %, that will comment out all the rest of the line after itself. This approach is really time-consuming if you want to insert long comments or just comment out a part of your document that you want to improve later. Using the verbatim package, to be loaded in the preamble as usual:
\usepackage{verbatim}
you can use an environment called comment that will comment out everything within itself. Here is an example:
This is another \begin{comment} rather stupid, but helpful \end{comment} example for embedding comments in your document. |
This is another example for embedding comments in your document. |
Note that this won’t work inside complex environments, like math for example. You may be wondering, why should I load a package called verbatim to have the possibility to add comments? The answer is straightforward: commented text is not interpreted by the compiler just like verbatim text, the only difference is that verbatim text is introduced within the document, while the comment is just dropped.
Alternatively, you can define a comment command, by adding the following to the document's preamble:
\newcommand{\comment}[1]{}
Then, to comment out text, simply do something like this:
\comment{ This is a long comment and can extend over multiple lines, etc. }
Quoting text
LaTeX provides several environments for quoting text, they have small differences and they are aimed for different types of quotations. All of them are indented on either margin, and you will need to add your own quotation marks if you want them. The provided environments are:
quote- for a short quotation, or a series of small quotes, separated by blank lines.
quotation- for use with longer quotes, of more than one paragraph, because it indents the first line of each paragraph.
verse- is for quotations where line breaks are important, such as poetry. Once in, new stanzas are created with a blank line, and new lines within a stanza are indicated using the newline command,
\\. If a line takes up more than one line on the page, then all subsequent lines are indented until explicitly separated with\\.
Abstracts
In scientific publications it is customary to start with an abstract which gives the reader a quick overview of what to expect. LaTeX provides the abstract environment for this purpose. It is available in article and report document classes; it's not available in the book, but it's quite simple to create your own if you really need it.
List Structures
Lists often appear in documents, especially academic, as their purpose is often to present information in a clear and concise fashion. List structures in Latex are simply environments which essentially come in three flavors: itemize, enumerate and description.
All lists follow the basic format:
\begin{list_type} \item The first item \item The second item \item The third etc \ldots \end{list_type}
All three of these types of lists can have multiple paragraphs per item: just type the additional paragraphs in the normal way, with a blank line between each. So long as they are still contained within the enclosing environment, they will automatically be indented to follow underneath their item.
Itemize
This environment is for your standard bulleted list of items.
\begin{itemize} \item The first item \item The second item \item The third etc \ldots \end{itemize} |
Enumerate
The enumerate environment is for ordered lists, where by default, each item is numbered sequentially.
\begin{enumerate} \item The first item \item The second item \item The third etc \ldots \end{enumerate} |
Description
The description environment is slightly different. You can specify the item label by passing it as an optional argument (although optional, it would look odd if you didn't include it!). Ideal for a series of definitions, such as a glossary.
\begin{description} \item[First] The first item \item[Second] The second item \item[Third] The third etc \ldots \end{description} |
Sometimes you want a description where the text begins on a new line. This cannot easily be done with \\. The trick is to use \hfill.
\begin{description} \item[First] \hfill \\ The first item \item[Second] \hfill \\ The second item \item[Third] \hfill \\ The third etc \ldots \end{description} |
Compacted lists using mdwlist
As you may have noticed, in standard LaTeX document classes, the vertical spacing between items, and above and below the lists as a whole, is more than between paragraphs: it may look odd if the descriptions are too short. If you want tightly-packed lists, use the mdwlist package (included in the mdwtools bundle), which provides "starred" versions of the previous environments, i.e. itemize*, enumerate* and description*. They work exactly in the same way, but the output is more compact.
Nested Lists
Latex will happily allow you to insert a list environment into an existing one (up to a depth of four). Simply begin the appropriate environment at the desired point within the current list. Latex will sort out the layout and any numbering for you.
\begin{enumerate} \item The first item \begin{enumerate} \item Nested item 1 \item Nested item 2 \end{enumerate} \item The second item \item The third etc \ldots \end{enumerate} |
Customizing Lists
Customizing many things in LaTeX is not really within the beginners domain. While not necessarily difficult in itself, because beginners are already overwhelmed with the array of commands and environments, moving on to more advanced topics runs the risk of confusion.
However, since the tutorial is on formatting, I shall still include a brief guide on customizing lists. Feel free to skip!
Customizing Line Spacing in Lists
Inside lists you can redefine some length/dimension variables of latex, for example using:
\begin{itemize} \setlength{\itemsep}{1pt} \setlength{\parskip}{0pt} \setlength{\parsep}{0pt} \item first item \item second item \end{itemize}
Alternatively, to create a unified look in your document you can define your own enumerate environment:
\newenvironment{my_enumerate} {\begin{enumerate} \setlength{\itemsep}{1pt} \setlength{\parskip}{0pt} \setlength{\parsep}{0pt}} {\end{enumerate}}
Customizing Enumerated Lists
The thing people want to change most often with Enumerated lists are the counters. Therefore, to go any further, a brief introduction to LaTeX counters is required. Anything that LaTeX automatically numbers, such as section headers, figures, and itemized lists, there is a counter associated with it that controls the numbering.
There are four individual counters that are associated with itemized lists, each one represents the four possible levels of nesting, which are called: enumi, enumii, enumiii, enumiv. In order to reset any of these counters in the middle of an enumeration simply use \setcounter. The counter is incremented by \item before it is printed. For example to reset enumi use:
\begin{enumerate} \setcounter{enumi}{4} \item fifth element \end{enumerate}
which prints as:
5. fifth element
Each counter also has a default format that dictates how it is displayed whenever LaTeX needs to print it. Such formats are specified using internal LaTeX commands:
| Command | Example |
| \arabic | 1, 2, 3 ... |
| \alph | a, b, c ... |
| \Alph | A, B, C ... |
| \roman | i, ii, iii ... |
| \Roman | I, II, III ... |
| \fnsymbol | Aimed at footnotes (see below), but prints a sequence of symbols. |
Each counter entity holds various bits of information about itself. To get to the numbered element, simply use \the followed immediately (i.e., no space) by the name of the counter, e.g., \theenumi. This is often referred to as the representation of a counter.
Now, that's most of the technicalities out of the way. To make changes to the formatting of a given level:
\renewcommand{\representation}{\format_command{counter}}
Admittedly, the generic version is not that clear, so a couple of examples will clarify:
%Redefine the first level \renewcommand{\theenumi}{\Roman{enumi}} \renewcommand{\labelenumi}{\theenumi} %Redefine the second level \renewcommand{\theenumii}{\Alph{enumii}} \renewcommand{\labelenumii}{\theenumii}
The method used above first explicitly changes the format used by the counter. However, the element that controls the label needs to be updated to reflect the change, which is what the second line does. Another way to achieve this result is this:
\renewcommand{\labelenumi}{\Roman{enumi}}
This simply redefines the appearance of the label, which is fine, providing that you do not intend to cross-reference to a specific item within the list, in which case the reference will be printed in the previous format. This issue does not arise in the first example.
Note that you can also add other symbols, such as parentheses and periods, before and after the counter. For instance, to create a list indexed by lower case letters with parentheses before and after the letter, you might enter the following:
\renewcommand{\labelenumi}{(\alph{enumi})}
Customizing Itemised Lists
Itemized lists are not as complex as they do not need to count. Therefore, to customize, you simply change the labels. It can be done manually for each entry with \item[ new symbol ], eg \item[$\star$].
The itemize labels are accessed via \labelitemi, \labelitemii, \labelitemiii, \labelitemiv, for the four respective levels.
\renewcommand{\labelitemi}{\textgreater}
The above example would set the labels for the first level to a greater than (>) symbol. Of course, the text symbols available in Latex are not very exciting. Why not use one of the ZapfDingbat symbols, as described in the Symbols section. Or use a mathematical symbol:
\renewcommand{\labelitemi}{$\star$}
Itemized list with tightly set items, that is with no vertical space between two consecutive items, can be created as follows.
\begin{itemize} \setlength{\itemsep}{0cm}% \setlength{\parskip}{0cm}% \item Item opening the list \item Item tightly following \end{itemize}
Details of Customizing Lists
Note that it is necessary that the \renewcommand appears after the \begin{document} instruction so the changes made are taken into account. This is needed for both enumerated and itemized lists.
Inline lists
Inline lists are a special case as they require the use of the paralist package which provides the inparaenum environment (with an optional formatting specification in square brackets):
To change the styles of the counter, tokens A, a, I, i, and 1 can be used in the optional argument to pruduce the counter with one of the styles \Alph, \alph, \Roman, \roman and \arabic. For example:
\begin{inparaenum}[(i)] |
| produces the labels (i), (ii), (iii) ... |
Footnotes
Footnotes are a very useful way of providing extra information to the reader. Usually, it is non-essential information which can be placed at the bottom of the page. This keeps the main body of text concise.
The footnote facility is easy to use. The command you need is: \footnote{text}. Do not leave a space between the command and the word where you wish the footnote marker to appear, otherwise Latex will process that space and will leave the output not looking as intended.
Creating a footnote is easy.\footnote{An example footnote.} |
Latex will obviously take care of typesetting the footnote at the bottom of the page. Each footnote is numbered sequentially - a process that, as you should have guessed by now, is automatically done for you.
It is possible to customize the footnote marking. By default, they are numbered sequentially (Arabic). However, without going too much into the mechanics of Latex at this point, it is possible to change this using the following command (which needs to be placed at the beginning of the document, or at least before the first footnote command is issued).
| \renewcommand{\thefootnote}{\arabic{footnote}} | Arabic numerals, e.g., 1, 2, 3... |
| \renewcommand{\thefootnote}{\roman{footnote}} | Roman numerals (lowercase), e.g., i, ii, iii... |
| \renewcommand{\thefootnote}{\Roman{footnote}} | Roman numerals (uppercase), e.g., I, II, III... |
| \renewcommand{\thefootnote}{\alph{footnote}} | Alphabetic (lowercase), e.g., a, b, c... |
| \renewcommand{\thefootnote}{\Alph{footnote}} | Alphabetic (uppercase), e.g., A, B, C... |
| \renewcommand{\thefootnote}{\fnsymbol{footnote}} | A sequence of nine symbols (try it and see!) |
Margin Notes
Margin Notes are not commonly used, but are included here for completeness. To insert a margin note use \marginpar{margin text}. For one-sided layout (simplex), the text will be placed in the right margin, starting from the line where it is defined. For two-sided layout (duplex), it will be placed in the outside margin and for two-column layout it will be placed in the nearest margin.
To swap the default side, use \reversemarginpar and margin notes will then be placed on the opposite side, which would be the inside margin for two-sided layout.
If the text of your marginpar depends on which margin it is put in (say it includes an arrow pointing at the text or refers to a direction as in "as seen to the left..."), you can use \marginpar[left text]{right text} to specify the variants.
To insert a margin note in an area that \marginpar can't handle, such as footnotes or equation environments, use the package marginnote.
Also see the package mparhack.
Summary
Phew! What a busy tutorial! A lot of material was covered here, mainly because formatting is such a broad topic. Latex is so flexible that we actually only skimmed the surface, as you can have much more control over the presentation of your document if you wish. Having said that, one of the purposes of Latex is to take away the stress of having to deal with the physical presentation yourself, so you need not get too carried away!
Page Layout
Latex and the document class will normally take care of 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, for your own documents, there are some obvious settings that you may wish to change: margins, page orientation and columns, to name but three. The purpose of this tutorial is to show you how to configure your pages.
Page Dimensions
A page in Latex is defined by myriad internal parameters. Each parameter corresponds to the length of an element of the page, for example, \paperheight is the physical height of the page. Here you can see a diagram showing all the variables defining the page:
|
It will not have been immediately obvious - because it doesn't really cause any serious problems - that the default page size for all standard document classes is US letter. This is shorter by 18 mm (about 3/4 inch), and slightly wider by 8 mm (about 1/4 inch), compared to A4 (which is the standard in almost all the rest of the world). As I said, it's not a great problem, and most printers will print the page without a hiccup. However, it is possible to specify alternative sizes.
\documentclass[a4paper]{article}
The above example illustrates how to pass the optional argument to the \documentclass, which will then modify the page dimensions accordingly. The standard document classes that are a part of Latex are built to be fairly generic, which is why you have the flexibility of specifying the page size. Other classes may have different options (or none at all). Normally, 3rd party classes come with some documentation to let you know.
Readers from a word processing background are probably thinking why there is so much white space surrounding the text. There is a good reason, and it's all down to readability. Have a look in a few books, and pick a few lines at random. Count the number of characters per line. I bet the average is about 66. Studies have shown that it's easier to read text when there are 60-70 characters per line - and it would seem that 66 is the optimal number. Therefore, the page margins are set to ensure that readability remains as good as possible. Also, white space is often left in the inner margin for the assumption that the document will be bound.
If you wish to change the margins of your document, there are many ways to do so:
- Simply use the
fullpagepackage for somewhat standardized smaller margins:
\usepackage{fullpage}
- Use the
a4widepackage for a page with A4 document size with smaller margins.
- Use the
geometrypackage. This package allows you to specify the 4 margins without needing to remember the particular page dimensions commands. It may be implemented as follows:
\usepackage[top=tlength, bottom=blength, left=llength, right=rlength]{geometry}
- Edit individual page dimension variables described above, using the
\addtolengthand\setlengthcommands. For instance,
\oddsidemargin=-1cm \setlength{\textwidth}{6.5in} \addtolength{\voffset}{-5pt}
Additionally, there are several packages designed to solve the problem of varying pages sizes, which override any defaults setup by the document class. One of the most versatile packages for page layout is the geometry package. For instance, to set the page size, add the following to your preamble:
\usepackage[a4paper]{geometry}
The geometry package has many pre-defined page sizes, like a4paper, built in. Others include: a0paper, a1paper, ..., a6paper, b0paper, b1paper, ..., b6paper, letterpaper, legalpaper, executivepaper.
To explicitly change the paper dimensions using the geometry package, the paperwidth and paperheight options can be used. For example:
\usepackage[margin=1in, paperwidth=5.5in, paperheight=8.5in]{geometry}
Page size issues
If you intend to get a pdf in the end, there are basically three ways:
TeX => PDF TeX => DVI => PDF TeX => DVI => PS => PDF
Which are in general obtained with
pdflatex myfile latex myfile dvipdf myfile dvips myfile -o myfile.ps ps2pdf myfile.ps myfile.pdf
With all the available Ghostscript versions, the safest way to always get the right paper size in the end is to add
\documentclass[...,a4paper,...]{...} \special{papersize=210mm,297mm}
to the tex file, -t a4 after dvips and -sPAPERSIZE=a4 after the ps2pdf. For pdflatex to work fine, using the package geometry usually works.
If you want US Letter instead, replace "210mm,297mm" by "8.5in,11in" and "a4" by "letter".
Page Orientation
When you talk about changing page orientation, it usually means changing to landscape mode, since portrait is the default. I shall introduce two slightly different styles of changing orientation.
The first is for when you want all of your document to be in landscape from the very beginning. There are various packages available to achieve this, but the one I prefer is the geometry package. All you need to do is call the package, with landscape as an option:
\usepackage[landscape]{geometry}
Although, if you intend to use geometry to set your paper size, don't add the \usepackage commands twice, simply string all the options together, separating with a comma:
\usepackage[a4paper,landscape]{geometry}
The second method is for when you are writing a document in portrait, but you have some contents, like a large diagram or table that would be displayed better on a landscape page. However, you still want the consistency of your headers and footers appearing the same place as the other pages.
The lscape package is for this very purpose. It supplies a landscape environment, and anything inside is basically rotated. No actual page dimensions are changed. This approach is more applicable to books or reports than to typical academic publications. Using pdflscape instead of lscape when generating a PDF document will make the page appear right side up when viewed: the single page that is in landscape format will be rotated, while the rest will be left in portrait orientation.
Also, to get a table to appear correctly on a landscaped page, one must place the tabular environment inside a table environment, which is itself inside the landscape environment. e.g., it should look like this:
\begin{landscape} \begin{table} \centering % optional, probably makes it look better to have it centered on the page \begin{tabular}{....} ....... \end{tabular} \end{table} \end{landscape}
Page Styles
Page styles in Latex terms refers not to page dimensions, but to the running headers and footers of a document. You may have noticed that in every example document produced for these tutorials, each page has its respective number printed at the bottom, even though not a single command has been issued to tell Latex to do it! That is because the document class in use has already defined the page style for you. Of course, you don't need to stick with the defaults if you don't want to.
There are two commands at your disposal for changing the page style. \pagestyle{style} will apply the specified style to the current and all subsequent pages. \thispagestyle{style} will only affect the current page. The possible styles are:
| empty | Both header and footer are clear |
| plain | Header is clear, but the footer contains the page number. |
| headings | Header displays page number and other information which the document class deems important, e.g., section headers. |
| myheadings | Similar to above, however, is possible to control the information in the header. |
An issue to look out for is that the major sectioning commands (\part, \chapter or \maketitle) specify a \thispagestyle{plain}. So, if you wish to suppress all styles by inserting a \pagestyle{empty} at the beginning of your document, then the style command at each section will override your initial rule, for those pages only. To achieve your intended result, you will have to follow the offending commands with \thispagestyle{empty}.
Customising with fancyhdr
The fancyhdr package, written by Piet van Oostrum, provides a few simple commands that allow you to customize the header and footer lines of your document. For a more complete guide, the author of the package produced this documentation.
The tricky problem when customizing headers and footers is to get things like running section and chapter names in there. LaTeX accomplishes this with a two-stage approach. In the header and footer definition, you use the commands \rightmark and \leftmark to represent the current section and chapter heading, respectively. The values of these two commands are overwritten whenever a chapter or section command is processed. For ultimate flexibility, the \chapter command and its friends do not redefine \rightmark and \leftmark themselves. They call yet another command (\chaptermark, \sectionmark, or \subsectionmark) that is responsible for redefining \rightmark and \leftmark.
If you want to change the look of the chapter name in the header line, you need only "renew" the \chaptermark command.
To begin, add the following lines to your preamble:
\usepackage{fancyhdr} \setlength{\headheight}{15.2pt} \pagestyle{fancy}
The second line will prevent LaTeX from giving a warning. Both the header and footer comprise three elements each according to its horizontal position (left, centre or right). To set their values, the following commands are available:
| \lhead[lh-even]{lh-odd} | \lfoot[lf-even]{lf-odd} |
| \chead[ch-even]{ch-odd} | \cfoot[cf-even]{cf-odd} |
| \rhead[rh-even]{rh-odd} | \rfoot[rf-even]{rf-odd} |
Hopefully, the behaviour of the above commands is fairly intuitive: if it has head in it, it affects the head etc, and obviously, l, c and r means left, centre and right respectively. Documents can be either one- or two-sided. Articles are by default one-sided, books are two-sided. Two-sided documents differentiate the left (even) and right (odd) pages, whereas one-sided do not.
Watch out: if you give long text in two different "parts" only in the footer or only in the header, you might see overlapping text, be careful. There are special commands you can use as arguments:
| \thepage | number of the current page |
| \leftmark | current chapter name printed like "CHAPTER 3. THIS IS THE CHAPTER TITLE" |
| \rightmark | current section name printed like "1.6. THIS IS THE SECTION TITLE" |
| \thesection | current section number |
Note that \leftmark and \rightmark convert the names to uppercase, whichever was the formatting of the text. If you want them to print the actual name of the chapter without converting it to uppercase use the following command:
\renewcommand{\chaptermark}[1]{\markboth{#1}{}} \renewcommand{\sectionmark}[1]{\markright{#1}{}}
now \leftmark and \rightmark will just print the name of the chapter and section, without number and without affecting the formatting. Moreover, with the following commands you can define the thickness of the decorative lines on both the header and the footer:
\renewcommand{\headrulewidth}{0.5pt} \renewcommand{\footrulewidth}{0pt}
The first line for the header, the second for the footer. Setting it to zero means that there will be no line.
An example:
\fancyhf{} \lhead{Andrew Roberts} \rhead{\today} \rfoot{\thepage}
It is often necessary to clear any defaults or a previous style definition, and the first line of the above example will do this. The commands are an alternative interface to customising the headers/footers that fancyhdr offers, and so by not passing anything to them, it assumes that you want it all blank.
The result of these commands will put my name at the top left, todays date at the top right, and the current page number at the bottom right of the page. Even if the document class was two-sided, because no optional text has been supplied for the even pages, the style will be used for all pages.
This approach a serious bad point: some pages like the title or the beginning of each chapter have no header or footer, but with the code we have shown every page will get the same output. There is a way to solve this problem: you can use the fancyplain style. If you do so, you can use the command \fancyplain{...}{...} inside \lhead{...} etc.
When LaTeX wants to create a page with an empty style, it will insert the first argument of fancyplain, in all the other cases it will use the second argument. So, an improved version of the previous code would be:
\pagestyle{fancyplain} \fancyhf{} \lhead{\fancyplain{}{Andrew Roberts}} \rhead{\fancyplain{}{\today}} \rfoot{\fancyplain{}{\thepage}}
It has the same behavior of the previous code, but you will get empty header and footer in the title and at the beginning of chapters.
For two-sided, it's common to mirror the style of opposite pages, you tend to think in terms of inner and outer. So, the same example as above for two-sided is:
\lhead[Andrew Roberts]{} \rhead[]{Andrew Roberts} \lhead[]{\today} \rhead[\today]{} \lfoot[\thepage]{} \rfoot[]{\thepage}
This is effectively saying my name is top outer, todays date is top inner, and current page number is bottom outer. You can use the fancyplain command within them for two-sided documents, too.
As an example, here is the complete code of a basic configuration you could use for a real document:
\usepackage{fancyhdr} \setlength{\headheight}{15pt} \pagestyle{fancyplain} \renewcommand{\chaptermark}[1]{\markboth{#1}{}} \lhead{\fancyplain{}{\thepage}} \chead{} \rhead{\fancyplain{}{\textit{\leftmark}}} \lfoot{} \cfoot{} \rfoot{}
NB. If you want to make the article class two-sided, use \documentclass[twoside]{article}.
Another approach with fancyhdr
If you want to get different style for even and odd pages, there is another possible way, still using fancyhdr. Start again with:
\fancyhf{}
it will just delete the current heading/footer configuration, so you can make your own. Now you can create what you want using the command \fancyhead for header and \fancyfoot for footer. They work in the same way, so we'll explain only the first one. The syntax is:
\fancyhead[selectors]{output you want}
The selectors are the following:
| E | even page |
| O | odd page |
| L | left side |
| C | centered |
| R | right side |
so CE will refer to the center of the even pages and RO to the right side of the odd pages. Whether it is header or footer, depends if you are using \fancyhead or \fancyfoot. You can use multiple selectors separated by a comma. Here is an example:
\fancyhead[CE]{Author's Name} \fancyhead[CO]{\today} \fancyfoot[LE,RO]{\thepage}
it will print author's name on the center of the header of the even pages, the date of the current day on the center of the odd pages and the current page number on the left size of even pages and on the right size of the odd pages. Finally, in order to have the pages at the beginning of any chapter really plain, you could redefine the plain style, for example to have a really plain page when you want. The command to use is \fancypagestyle{plain}{...} and the argument can contain all the commands explained before. An example is the following:
\fancypagestyle{plain}{ % \fancyhf{} % remove everything \renewcommand{\headrulewidth}{0pt} % remove lines as well \renewcommand{\footrulewidth}{0pt}}
Finally, here is the complete code of a possible style you could use for a two-sided document:
\usepackage{fancyhdr} \setlength{\headheight}{15pt} \pagestyle{fancy} \renewcommand{\chaptermark}[1]{\markboth{#1}{}} \renewcommand{\sectionmark}[1]{\markright{#1}{}} \fancyhf{} \fancyhead[LE,RO]{\thepage} \fancyhead[RE]{\textit{\nouppercase{\leftmark}}} \fancyhead[LO]{\textit{\nouppercase{\rightmark}}} \fancypagestyle{plain}{ % \fancyhf{} % remove everything \renewcommand{\headrulewidth}{0pt} % remove lines as well \renewcommand{\footrulewidth}{0pt}}
Page n of m
Some people like to put the current page number in context with the whole document. LaTeX only provides access to the current page number. However, you can use the lastpage package to find the total number of pages, like this:
\usepackage{lastpage} ... \cfoot{\thepage\ of \pageref{LastPage}}
Note the capital letters. Also, add a backslash after \thepage to ensure adequate space between the page number and 'of'. And recall, when using references, that you have to run LaTeX an extra time to resolve the cross-references.
Multi-column Pages
It is common to see articles and conference proceedings formatted with two columns of text. However, such publishers will usually provide you with their own document class, which automatically implements this format, without you having to do anything. It is very easy to format your page in this way. If you are using a standard Latex document class, then you can simply pass the optional argument twocolumn to the document class: \documentclass[twocolumn]{article} which will give the desired effect.
While this simple addition will do the job 9 out of 10 times, it is widely acknowledged that there are many limitations of this approach, and that the multicol package is much more useful for handling multiple columns. It has several advantages:
- Can support up to ten columns.
- Implements a multicols environment, therefore, it is possible to mix the number of columns within a document.
- Additionally, the environment can be nested inside other environments, such as
figure. Multicoloutputs balanced columns, whereby the columns on the final page will be of roughly equal length.- Vertical rules between columns can be customised.
- Column environments can be easily customised locally or globally.
Floats are not fully supported by this environment. It can only cope if you use the starred forms of the float commands (e.g., \begin{figure*} ) which makes the float span all columns. This is not hugely problematic, since floats of the same width as a column may be too small, and you would probably want to span them anyway.
To create a typical two-column layout:
\begin{multicols}{2} lots of text \end{multicols}
The parameter \columnseprule holds the width of the vertical rules. By default, the lines are omitted as this parameter is set to a length of 0pt. Do the following before the beginning of the environment:
\setlength{\columnseprule}{1pt}
This will draw a thin line of 1pt in width. A thick line would not look very pleasing, however, you are free to put in any length of your choosing. Also, to change the horizontal space in between columns (the default is set at 10pt, which is quite narrow) then you need to change the \columnsep parameter:
\setlength{\columnsep}{20pt}
Manual Page Formatting
There may be instances, especially in very long documents, such as books, that Latex will not get all page breaks looking as good as it could. It may, therefore, be necessary to manually tweak the page formatting. Of course, you should only do this at the very final stage of producing your document, once all the content is complete. Latex offers the following:
| \newline | Breaks the line at the point of the command. |
| \\ | Breaks the line at the point of the command, it's a shorter version of the previous command but it does exactly the same |
| \\* | Breaks the line at the point of the command and additionally prohibits a page break after the forced line break |
| \linebreak[number] | Breaks the line at the point of the command. The number you provide as an argument represents the priority of the command in a range from 0 (it will be easily ignored) to 4 (do it anyway). LaTeX will try to produce the best line breaks possible, meeting its high standards. If it cannot, it will decide whether including the linebreak or not according to the priority you have provided. |
| \newpage | Ends the current page and starts a new one. |
| \pagebreak[number] | Breaks the current page at the point of the command. The optional number argument sets the priority in a scale from 0 to 4. |
| \nopagebreak[number] | Stops the page being broken at the point of the command. The optional number argument sets the priority in a scale from 0 to 4. |
| \clearpage | Ends the current page and causes any floats encountered in the input, but yet to appear, to be printed. |
Widows and orphans
In professional books, it's not desirable to have single lines at the beginning or end of a page. In typesetting such situations are called 'widows' and 'orphans'. Normally it is possible that widows and orphans appear in LaTeX documents. You can try to deal with them using manual page formatting, but there's also an automatic solution.
LaTeX has a parameter for 'penalty' for widows and orphans ('club lines' in LaTeX terminology). With the greater penalty LaTeX will try more to avoid widows and orphans. You can try to increase these penalties by putting following commands in your document preamble:
\widowpenalty=300 \clubpenalty=300
If this does not help, you can try increasing these values even more, to 1000.
It also helps to have rubber band values for the space between paragraphs:
\setlength{\parskip}{3ex plus 2ex minus 2ex}
Summary
This tutorial is relatively short, largely due to the fact that the whole LaTeX ethos is to concentrate on the content, and let LaTeX (and/or other typographers who have developed suitable document classes) decide on the best presentation. The next step to achieve greater control of page layout is to set about designing your own class. Unfortunately, that is not a straightforward task, and is often best left to the professionals!
Mathematics
One of the greatest motivating forces for Donald Knuth when he began developing the original TeX system was to create something that allowed simple construction of mathematical formulas, whilst looking professional when printed. The fact that he succeeded was most probably why TeX (and later on, LaTeX) became so popular within the scientific community. Regardless of the history, typesetting mathematics is one of LaTeX's greatest strengths. It is also a large topic due to the existence of so much mathematical notation.
If you are writing a document that needs only a few simple mathematical formulas, then you can generally use plain LaTeX: it will give you most of the tools you need. However, if you are writing a scientific document that contains numerous complicated formulas, it is highly recommended that you use the amsmath package, which introduces several new commands that are more powerful and flexible than the ones provided by plain LaTeX. To use this, include:
\usepackage{amsmath} |
in the preamble of the document.
Mathematics environments
LaTeX needs to know beforehand that the subsequent text does in fact contain mathematical elements. This is because LaTeX typesets maths notation differently than normal text. Therefore, special environments have been declared for this purpose. They can be distinguished into two categories depending on how they are presented:
- text - text formulas are displayed in-line, that is, within the body of text where it is declared. e.g., I can say that a + a = 2a within this sentence.
- displayed - displayed formulas are separate from the main text.
As maths require special environments, there are naturally the appropriate environment names you can use in the standard way. Unlike most other environments, however, there are some handy shorthands to declaring your formulas. The following table summarizes them:
| Type | Environment | LaTeX shorthand | TeX shorthand |
|---|---|---|---|
| Text | \begin{math}...\end{math} |
\(...\) |
$...$ |
| Displayed | \begin{displaymath}...\end{displaymath} or
|
\[...\] |
$$...$$ |
Note: Using the $$...$$ should be avoided, as it may cause problems, particularly with the AMS-LaTeX macros. Furthermore, should a problem occur, the error messages may not be helpful.
Additionally, there is a second possible environment for the displayed type of formulas: equation. The difference between this and displaymath is that equation also adds sequential equation numbers by the side.
If you are typing text normally, you are said to be in text mode, while you are typing within one of those mathematical environments, you are said to be in math mode, that has some differences compared to the text mode:
- Most spaces and line breaks do not have any significance, as all spaces are either derived logically from the mathematical expressions, or have to be specified with special commands such as
\quad - Empty lines are not allowed. Only one paragraph per formula.
- Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula (normal upright font and normal spacing) then you have to enter the text using dedicated commands.
Symbols
Mathematics has lots and lots of symbols! If there is one aspect of maths that is difficult in LaTeX it is trying to remember how to produce them. There are of course a set of symbols that can be accessed directly from the keyboard:
+ - = ! / ( ) [ ] < > | ' :
Beyond those listed above, distinct commands must be issued in order to display the desired symbols. And there are a lot! Greek letters, set and relations symbols, arrows, binary operators, etc. Too many to remember, and in fact, they would overwhelm this tutorial if I tried to list them all. Therefore, for a complete reference document, see the external link at the bottom of the page.
\[ \forall x \in X, \quad \exists y \leq \epsilon \] |
![]() |
Greek letters
Greek letters are commonly used in mathematics, and they are very easy to type in math mode. You just have to type the name of the letter after a backslash: if the first letter is lowercase, you will get a lowercase Greek letter, if the first letter is uppercase (and only the first letter), then you will get an uppercase letter. Note that some uppercase Greek letters look like Latin ones, so they are not provided by LaTeX (e.g. uppercase Alpha and Beta are just "A" and "B" respectively). Theta, Phi, and Sigma are provided in two different versions:
\[ \alpha, \beta, \gamma, \delta, \epsilon, \zeta, \mu, \theta, \vartheta, \phi, \varphi, \omega, \sigma, \varsigma, \Gamma, \Delta, \Theta, \Phi, \Omega \] |
![]() |
Operators
An operator is a function that is written as a word: e.g. trigonometric functions (sin, cos, tan), logarithms and exponentials (log, exp). LaTeX has many of these defined as commands:
\[ \cos (2\theta) = \cos^2 \theta - \sin^2 \theta \] |
![]() |
For certain operators such as limits, the subscript is placed underneath the operator:
\[ \lim_{x \to \infty} \exp(-x) = 0 \] |
![]() |
For the modular operator there are two commands: \bmod and \pmod:
\[ a \bmod b \] |
![]() |
\[ x \equiv a \pmod b \] |
![]() |
To use operators which are not pre-defined, such as argmax, see custom operators
Powers and indices
Powers and indices are equivalent to superscripts and subscripts in normal text mode. The caret (^) character is used to raise something, and the underscore (_) is for lowering. If more than one expression is raised or lowered, they should be grouped using curly braces ({ and }).
\[ k_{n+1} = n^2 + k_n^2 - k_{n-1} \] |
![]() |
Fractions and Binomials
A fraction is created using the \frac{numerator}{denominator} command. (For those who need their memories refreshed, that's the top and bottom respectively!). Likewise, the binomial coefficient (aka the Choose function) may be written using the \binom command
\[ \frac{n!}{k!(n-k)!} = \binom{n}{k} \] |
![]() |
You can also embed fractions within fractions:
\[ \frac{\frac{1}{x}+\frac{1}{y}}{y-z} \] |
![]() |
Note that when appearing inside another fraction, or in inline text
, a fraction is noticeably smaller than in displayed mathematics. The \tfrac and \dfrac commands[1] force the use of the respective styles (similarly the \tbinom and \dbinom commands do the same for the binomial coefficient).
For relatively simple fractions, it may be more aesthetically pleasing to use powers and indices:
\[ ^3/_7 \] |
![]() |
Roots
The sqrt command creates a square root surrounding an expression. It accepts an optional argument specified in square brackets ([ and ]) to change magnitude:
\[ \sqrt{\frac{a}{b}} \] |
![]() |
\[ \sqrt[n]{1+x+x^2+x^3+\ldots} \] |
![]() |
Some people prefer writing the square root "closing" it over its content. This method arguably makes it more clear just what is in the scope of the root sign. This habit is not normally used while writing with the computer because the text is supposed to be clear anyway, but if you want to change the output of the square root anyway, LaTeX gives you this possibility. Just add the following code in the preamble of your document:
% New definition of square root: % it renames \sqrt as \oldsqrt \let\oldsqrt\sqrt % it defines the new \sqrt in terms of the old one \def\sqrt{\mathpalette\DHLhksqrt} \def\DHLhksqrt#1#2{% \setbox0=\hbox{$#1\oldsqrt{#2\,}$}\dimen0=\ht0 \advance\dimen0-0.2\ht0 \setbox2=\hbox{\vrule height\ht0 depth -\dimen0}% {\box0\lower0.4pt\box2}} |
This TeX code first renames the \sqrt command as \oldsqrt, then redefines \sqrt in terms of the old one, adding something more. The new square root can be seen in the picture on the right, compared to the old one. Unfortunately this code won't work if you want to use multiple roots: if you try to write
as \sqrt[b]{a} after you used the code above, you'll just get a wrong output. 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.
Sums and integrals
The \sum and \int commands insert the sum and integral symbols respectively, with limits specified using the caret (^) and underscore (_):
\[ \sum_{i=1}^{10} t_i \] |
![]() |
\[ \int_0^\infty e^{-x} \, dx \] |
![]() |
There are many other "big" commands which operate in a similar manner:
\sum |
![]() |
\prod |
![]() |
\coprod |
![]() |
||
\bigoplus |
![]() |
\bigotimes |
![]() |
\bigodot |
![]() |
||
\bigcup |
![]() |
\bigcap |
![]() |
\biguplus |
![]() |
||
\bigsqcup |
![]() |
\bigvee |
![]() |
\bigwedge |
![]() |
||
\int |
![]() |
\oint |
![]() |
\iint[1] |
![]() |
||
\iiint[1] |
![]() |
\iiiint[1] |
![]() |
\idotsint[1] |
![]() |
For more integral symbols, including those not included by default in the Computer Modern font, try the esint package. The \substack command[1] allows the use of \\ to write the limits over multiple lines:
\[ \sum_{\substack{ 0<i<m \\ 0<j<n }} P(i,j) \] |
![]() |
If you want the limits of an integral to be specified above and below the symbol (like the sum), use the \limits command:
\[ \int\limits_a^b \] |
![]() |
However if you want this to apply to ALL integrals, it is preferable to specify the intlimits option when loading the amsmath package:
\usepackage[intlimits]{amsmath} |
Brackets, braces and delimiters
The use of delimiters such as brackets soon becomes important when dealing with anything but the most trivial equations. Without them, formulas can become ambiguous. Also, special types of mathematical structures, such as matrices, typically rely on delimiters to enclose them.
There are a variety of delimiters available for use in LaTeX:
\[ () \, [] \, \{\} \, || \, \|\| \, \langle\rangle \, \lfloor\rfloor \, \lceil\rceil \] |
![]() |
Automatic sizing
Very often mathematical features will differ in size, in which case the delimiters surrounding the expression should vary accordingly. This can be done automatically using the left and right commands. Any of the previous delimiters may be used in combination with these:
\[ \left(\frac{x^2}{y^3}\right) \] |
![]() |
If a delimiter on only one side of an expression is required, then an invisible delimiter on the other side may be denoted using a period (.).
Manual sizing
In certain cases, the sizing produced by the left and right commands may not be desirable, or you may simply want finer control over the delimiter sizes. In this case, the big, Big, bigg and Bigg modifier commands may be used:
\[ ( \big( \Big( \bigg( \Bigg( \] |
![]() |
Matrices and arrays
A basic matrix may be created using the matrix environment[1]: in common with other table-like structures, entries are specified by row, with columns separated using an ampersand (&) and a new rows separated with a double backslash (\\)
\[ \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \end{matrix} \] |
![]() |
However matrices are usually enclosed in delimiters of some kind, and while it is possible to use the \left and \right commands, there are various other predefined environments which automatically include delimiters:
| Environment name | Surrounding delimiter |
|---|---|
pmatrix[1] |
![]() |
bmatrix[1] |
![]() |
Bmatrix[1] |
![]() |
vmatrix[1] |
![]() |
Vmatrix[1] |
![]() |
When writing down arbitrary sized matrices, it is common to use horizontal, vertical and diagonal triplets of dots (known as ellipses) to fill in certain columns and rows. These can be specified using the \cdots, \vdots and \ddots respectively:
\[ A_{m,n} = \begin{pmatrix} a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\ a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m,1} & a_{m,2} & \cdots & a_{m,n} \end{pmatrix} \] |
![]() |
In some cases you may want to have finer control of the alignment within each column, or want to insert lines between columns or rows. This can be achieved using the array environment, which is essentially a math-mode version of the tabular environment, which requires that the columns be pre-specified:
\[ \begin{array}{c|c} 1 & 2 \\ \hline 3 & 4 \end{array} \] |
![]() |
Adding text to equations
The math environment differs from the text environment in the representation of text. Here is an example of trying to represent text within the math environment:
\[ 50 apples \times 100 apples = lots of apples^2 \] |
![]() |
There are two noticeable problems: there are no spaces between words or numbers, and the letters are italicized and more spaced out than normal. Both issues are simply artifacts of the maths mode, in that it treats it as a mathematical expression: spaces are ignored (LaTeX spaces mathematics according to its own rules), and each character is a separate element (so are not positioned as closely as normal text).
There are a number of ways that text can be added properly. The typical way is to wrap the text with the \text{...} command [1] (a similar command is \mbox{...}, though this causes problems with subscripts, and has a less descriptive name). Let's see what happens when the above equation code is adapted:
\[ 50 \text{apples} \times 100 \text{apples} = \text{lots of apples}^2 \] |
![]() |
The text looks better. However, there are no gaps between the numbers and the words. Unfortunately, you are required to explicitly add these. There are many ways to add spaces between maths elements, but for the sake of simplicity you may literally add the space character in the affected \text(s) itself (just before the text.)
\[ 50 \text{ apples} \times 100 \text{ apples} = \text{lots of apples}^2 \] |
![]() |
Formatted text
Using the \text is fine and gets the basic result. Yet, there is an alternative that offers a little more flexibility. You may recall the introduction of font formatting commands, such as \textrm, \textit, \textbf, etc. These commands format the argument accordingly, e.g., \textbf{bold text} gives bold text. These commands are equally valid within a maths environment to include text. The added benefit here is that you can have better control over the font formatting, rather than the standard text achieved with \text.
\[ 50 \textrm{ apples} \times 100 \textbf{ apples} = \textit{lots of apples}^2 \] |
![]() |
Formatting mathematics symbols
So we can format text, what about formatting mathematics? There are a set of formatting commands very similar to the font formatting ones just used, except they are aimed specifically for text in maths mode:
| LaTeX command | Sample | Description | Common use |
|---|---|---|---|
\mathnormal{…} |
![]() |
the default math font | most mathematical notation |
\mathrm{…} |
![]() |
this is the default or normal font, unitalicised | units of measurement, one word functions |
\mathit{…} |
![]() |
italicised font | |
\mathbf{…} |
![]() |
bold font | vectors |
\mathsf{…} |
![]() |
Sans-serif | |
\mathtt{…} |
ABCDEFabcdef123456 | Monospace (fixed-width) font | |
\mathcal{…} |
![]() |
Calligraphy (uppercase only) | often used for sheaves/schemes and categories |
\mathfrak{…}[2] |
![]() |
Fraktur | Almost canonical font for Lie algebras |
\mathbb{…}[2] |
![]() |
Blackboard bold | Used to denote special sets (e.g. real numbers) |
\mathscr{…}[3] |
Script |
The maths formatting commands can be wrapped around the entire equation, and not just on the textual elements: they only format letters, numbers, and uppercase Greek, and the rest of the maths syntax is ignored.
To bold lowercase Greek or other symbols use the \boldsymbol command[1]; this will only work if there exists a bold version of the symbol in the current font. As a last resort there is the \pmb command[1] (poor mans bold): this prints multiple versions of the character slightly offset against each other
\[ \boldsymbol{\beta} = (\beta_1,\beta_2,\ldots,\beta_n) \] |
![]() |
To change the size of the fonts in math mode, see Changing font size.
Accents
So what to do when you run out of symbols and fonts? Well the next step is to use accents:
a' |
![]() |
a'' |
![]() |
a''' |
![]() |
a'''' |
![]() |
|||
\hat{a} |
![]() |
\bar{a} |
![]() |
\check{a} |
![]() |
\tilde{a} |
![]() |
|||
\grave{a} |
![]() |
\acute{a} |
![]() |
\breve{a} |
![]() |
\vec{a} |
![]() |
|||
\dot{a} |
![]() |
\ddot{a} |
![]() |
\dddot{a}[1] |
\ddddot{a}[1] |
|||||
\not{a} |
![]() |
\mathring{a} |
\widehat{AAA} |
![]() |
\widetilde{AAA} |
Plus and minus signs
Latex deals with the + and − signs in two possible ways. The most common is as a binary operator. When two maths elements appear either side of the sign, it is assumed to be a binary operator, and as such, allocates some space either side of the sign. The alternative way is a sign designation. This is when you state whether a mathematical quantity is either positive or negative. This is common for the latter, as in maths, such elements are assumed to be positive unless a - is prefixed to it. In this instance, you want the sign to appear close to the appropriate 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 before the operator using {}. This can be useful if you are writing multiple-line formulas, and a new line could start with a = or a +, for example, then you can fix some strange alignments adding the invisible character where necessary.
Controlling horizontal spacing
Latex is obviously pretty good at typesetting maths—it was one of the chief aims of the core Tex system that Latex extends. However, it can't always be relied upon to accurately interpret formulas in the way you did. It has to make certain assumptions when there are ambiguous expressions. The result tends to be slightly incorrect horizontal spacing. In these events, the output is still satisfactory, yet, any perfectionists will no doubt wish to fine-tune their formulas to ensure spacing is correct. These are generally very subtle adjustments.
There are other occasions where Latex has done its job correctly, but you just want to add some space, maybe 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.
\[ f(n) = \left\{ \begin{array}{l l} n/2 & \quad \text{if $n$ is even}\\ -(n+1)/2 & \quad \text{if $n$ is odd}\\ \end{array} \right. \] |
|
Latex has defined two commands that can be used anywhere in documents (not just maths) to insert some horizontal space. They are \quad and \qquad
A \quad is a space equal to the current font size. So, if you are using an 11pt font, then the space provided by \quad 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 separation between the maths and the text.
OK, so back to the fine tuning as mentioned at the beginning of the document. A good example would be displaying the simple equation for the indefinite integral of y with respect to x:

If you were to try this, you may write:
\[ \int y \mathrm{d}x \] |
|
However, this doesn't give the correct result. Latex doesn't respect the white-space left in the code to signify that the y and the dx are independent entities. Instead, it lumps them altogether. A \quad would clearly be overkill is this situation—what is needed are some small spaces to be utilized in this type of instance, and that's what Latex provides:
| Command | Description | Size |
|---|---|---|
| \, | small space | 3/18 of a quad |
| \: | medium space | 4/18 of a quad |
| \; | large space | 5/18 of a quad |
| \! | negative space | -3/18 of a quad |
NB you can use more than one command in a sequence to achieve a greater space if necessary.
So, to rectify the current problem:
| \int y\, \mathrm{d}x |
|
| \int y\: \mathrm{d}x |
|
| \int y\; \mathrm{d}x |
|
The negative space may seem like an odd thing to use, however, it wouldn't be there if it didn't have some use! Take the following example:
\[\left( \begin{array}{c} n \\ r \end{array} \right) = \frac{n!}{r!(n-r)!} \] |
|
The matrix-like expression for representing binomial coefficients is too padded. There is too much space between the brackets and the actual contents within. This can easily be corrected by adding a few negative spaces after the left bracket and before the right bracket.
\[\left(\! \begin{array}{c} n \\ r \end{array} \!\right) = \frac{n!}{r!(n-r)!} \] |
|
In any case, adding some spaces manually should be avoided whenever possible: it makes the source code more complex and it's against the basic principles of a What You See is What You Mean approach. The best thing to do is to define some commands using all the spaces you want and then, when you use your command, you don't have to add any other space. Later, if you change your mind about the length of the horizontal space, you can easily change it modifying only the command you defined before. Let us use an example: you want the d of a dx in an integral to be in roman font and a small space away from the rest. If you want to type an integral like \int x \; \mathrm{d} x, you can define a command like this:
\newcommand{\dd}{\; \mathrm{d}}
in the preamble of your document. We have chosen \dd just because it reminds the "d" it replaces and it is fast to type. Doing so, the code for your integral becomes \int x \dd x. Now, whenever you write an integral, you just have to use the \dd instead of the "d", and all your integrals will have the same style. If you change your mind, you just have to change the definition in the preamble, and all your integrals will be changed accordingly.
Advanced Mathematics: AMS Math package
The AMS (American Mathematical Society) mathematics package is a powerful package that creates an higher layer of abstraction over mathematical LaTeX language; if you use it it will make your life easier. Some commands amsmath introduces will make other plain LaTeX commands obsolete: in order to keep consistency in the final output you'd better use amsmath commands whenever possible. If you do so, you will get an elegant output without worrying about alignment and other details, keeping your source code readable. If you want to use it, you have to add this in the preamble:
\usepackage{amsmath}
Introducing text and dots in formulas
Amsmath defines also the \dots command, that is a generalization of the existing \ldots. You can use \dots in both text and math mode and LaTeX will replace it with three dots "…" but it will decide according to the context whether to put it on the bottom (like \ldots) or centered (like \cdots).
Dots
LaTeX gives you several commands to insert dots in your formulas. This can be particularly useful if you have to type big matrices omitting elements. First of all, here are the main dots-related commands LaTeX provides:
| Code | Output | Comment |
|---|---|---|
| \dots | ![]() |
generic dots, to be used in text (outside formulas as well). It automatically manages whitespaces before and after itself according to the context, it's a higher level command. |
| \ldots | ![]() |
the output is similar to the previous one, but there is no automatic whitespace management; it works at a lower level. |
| \cdots | ![]() |
These dots are centered relative to the height of a letter. There is also the binary multiplication operator, \cdot, mentioned below. |
| \vdots | ![]() |
vertical dots |
| \ddots | ![]() |
diagonal dots |
| \hdotsfor{n} | ![]() |
to be used in matrices, it creates a row of dots spanning n columns. |
List of Mathematical Symbols
All the pre-defined mathematical symbols from the \TeX\ package are listed below. More symbols are available from extra packages.
| Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script |
|---|---|---|---|---|---|---|---|---|---|
![]() |
\leq | ![]() |
\geq | ![]() |
\equiv | ![]() |
\models | ![]() |
\prec |
![]() |
\succ | ![]() |
\sim | ![]() |
\perp | ![]() |
\preceq | ![]() |
\succeq |
![]() |
\simeq | ![]() |
\mid | ![]() |
\ll | ![]() |
\gg | ![]() |
\asymp |
![]() |
\parallel | ![]() |
\subset | ![]() |
\supset | ![]() |
\approx | ![]() |
\bowtie |
![]() |
\subseteq | ![]() |
\supseteq | ![]() |
\cong | ![]() |
\sqsubset | ![]() |
\sqsupset |
![]() |
\neq | ![]() |
\smile | ![]() |
\sqsubseteq | ![]() |
\sqsupseteq | ![]() |
\doteq |
![]() |
\frown | ![]() |
\in | ![]() |
\ni | ![]() |
\propto | ![]() |
= |
![]() |
\vdash | ![]() |
\dashv | ![]() |
< | ![]() |
> |
| Symbol | Script |
|---|---|
and ![]() |
\Alpha and \alpha |
and ![]() |
\Beta and \beta |
and ![]() |
\Gamma and \gamma |
and ![]() |
\Delta and \delta |
, and ![]() |
\Epsilon, \epsilon and \varepsilon |
and ![]() |
\Zeta and \zeta |
and ![]() |
\Eta and \eta |
, and ![]() |
\Theta, \theta and \vartheta |
and ![]() |
\Iota and \iota |
and ![]() |
\Kappa and \kappa |
and ![]() |
\Lambda and \lambda |
and ![]() |
\Mu and \mu |
and ![]() |
\Nu and \nu |
and ![]() |
\Xi and \xi |
, and ![]() |
\Pi, \pi and \varpi |
, and ![]() |
\Rho, \rho and \varrho |
, and ![]() |
\Sigma, \sigma and \varsigma |
and ![]() |
\Tau and \tau |
and ![]() |
\Upsilon and \upsilon |
, , and ![]() |
\Phi, \phi and \varphi |
and ![]() |
\Chi and \chi |
and ![]() |
\Psi and \psi |
and ![]() |
\Omega and \omega |
| Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script |
|---|---|---|---|---|---|---|---|
![]() |
\pm | ![]() |
\cap | ![]() |
\diamond | ![]() |
\oplus |
![]() |
\mp | ![]() |
\cup | ![]() |
\bigtriangleup | ![]() |
\ominus |
![]() |
\times | ![]() |
\uplus | ![]() |
\bigtriangledown | ![]() |
\otimes |
![]() |
\div | ![]() |
\sqcap | ![]() |
\triangleleft | ![]() |
\oslash |
![]() |
\ast | ![]() |
\sqcup | ![]() |
\triangleright | ![]() |
\odot |
![]() |
\star | ![]() |
\vee | ![]() |
\bigcirc | ![]() |
\circ |
![]() |
\wedge | ![]() |
\dagger | ![]() |
\bullet | ![]() |
\setminus |
![]() |
\ddagger | ![]() |
\cdot | ![]() |
\wr | ![]() |
\amalg |
| Symbol | Script |
|---|---|
![]() |
\exists |
![]() |
\forall |
![]() |
\neg |
and ![]() |
\in and \notin |
![]() |
\ni |
![]() |
\land |
![]() |
\lor |
![]() |
\implies |
![]() |
\iff |
![]() |
\emptyset |
Summary
As you can begin to see, typesetting maths can be tricky at times. However, because Latex provides so much control, you can get professional quality mathematics typesetting for relatively little effort (once you've had a bit of practice, of course!). It would be possible to keep going and going with maths topics because it seems potentially limitless. However, with this tutorial, you should be able to get along sufficiently.
Notes
- ↑ a b c d e f g h i j k l m n o p q r requires the
amsmathpackage - ↑ a b requires amsfonts or amssymb packages
- ↑ require mathrsfs package
Further reading
- meta:Help:Displaying a formula: Wikimedia uses a subset of LaTeX commands.
External links
Theorems
With "theorem" we can mean any kind of labelled enunciation that we want to look separated from the rest of the text and with sequential numbers next to it. This approach is commonly used for theorems in mathematics, but can be used for anything. LaTeX provides a command that will let you easily define any theorem-like enunciation.
Basic theorems
First of all, make sure you have the amsthm package enabled:
\usepackage{amsthm}
The easiest is the following:
\newtheorem{name}{Printed output}
put it in the preamble. The first argument is the name you will use to reference it, the second argument is the output LaTeX will print whenever you use it. For example:
\newtheorem{mydef}{Definition}
will define the mydef environment; if you use it like this:
\begin{mydef} Here is a new definition \end{mydef}
It will look like this:
- Definition 3 Here is a new definition
with line breaks separating it from the rest of the text.
Theorem counters
Often the counters are determined by section, for example "Theorem 2.3" refers to the 3rd theorem in the 2nd section of a document. In this case, specify the theorem as follows:
\newtheorem{name}{Printed output}[numberby]
where numberby specifies the section level (section/subsection/etc.) at which the numbering is to take place.
By default, each theorem uses its own counter. However it is common for similar types of theorems (e.g. Theorems, Lemmas and Corollaries) to share a counter. In this case, define subsequent theorems as:
\newtheorem{name}[counter]{Printed output}
where counter is the name of the counter to be used. Usually this will be the name of the master theorem.
You can also create a theorem environment that is not numbered by using the newtheorem* command[1]. For instance,
\newtheorem*{mydef}{Definition}
defines the mydef environment, which will generate definitions without numbering. This requires amsthm package.
Proofs
The proof environment[1] can be used for adding the proof of a theorem. The basic usage is:
\begin{proof} Here is my proof \end{proof}
It just adds Proof in italics at the beginning of the text 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 with the right argument and the word Proof printed in the output will be translated accordingly; anyway, in the source the name of the environment remains proof.
If you would like to manually name the proof, include the name in square brackets:
\begin{proof}[Proof of important theorem] Here is my important proof \end{proof}
If the last line of the proof is displayed math then the Q.E.D. symbol will appear on a subsequent empty line. To put the Q.E.D. symbol at the end of the last line, use the \qedhere command:
\begin{proof} Here is my proof: \[ a^2 + b^2 = c^2 \qedhere \] \end{proof}
To use a custom Q.E.D. symbol, redefine the \qedsymbol command. To hide the Q.E.D. symbol altogether, redefine it to be blank:
\renewcommand{\qedsymbol}{}
Theorem styles
It adds the possibility to change the output of the environments defined by \newtheorem using the \theoremstyle command[1] command in the header:
\theoremstyle{stylename}
the argument is the style you want to use. All subsequently defined theorems will use this style. Here is a list of the possible pre-defined styles:
| stylename | Description |
|---|---|
| plain | Used for theorems, lemmas, propositions, etc. (default) |
| definition | Used for definitions and examples |
| remark | Used for remarks and notes |
Custom styles
To define your own style, the use the \newtheoremstyle command[1]:
\newtheoremstyle{stylename}% name of the style to be used {spaceabove}% measure of space to leave above the theorem. E.g.: 3pt {spacebelow}% measure of space to leave below the theorem. E.g.: 3pt {bodyfont}% name of font to use in the body of the theorem {indent}% measure of space to indent {headfont}% name of head font {headpunctuation}% punctuation between head and body {headspace}% space after theorem head; " " = normal interword space {headspec}% Manually specify head
(Any arguments that are left blank will assume their default value). Here is an example headspec:
\thmname{#1}\thmnumber{ #2}:\thmnote{ #3}
which would look something like:
Definition 2: Topology
for the following:
\begin{definition}{Topology}...
(The note argument, which in this case is Topology, is always optional, but will not appear by default unless you specify it as above in the head spec).
Conflicts
The theorem environment conflicts with other environments, for example wrapfigure. A work around is to redefine theorem, for example the following way:
% Fix latex \def\smallskip{\vskip\smallskipamount} \def\medskip{\vskip\medskipamount} \def\bigskip{\vskip\bigskipamount} % Hand made theorem \newcounter{thm}[section] \renewcommand{\thethm}{\thesection.\arabic{thm}} \def\claim#1{\par\medskip\noindent\refstepcounter{thm}\hbox{\bf \arabic{chapter}.\arabic{section}.\arabic{thm}. #1.} \it\ %\ignorespaces } \def\endclaim{ \par\medskip} \newenvironment{thm}{\claim}{\endclaim}
In this case theorem looks like:
\begin{thm}{Claim}\label{lyt-prob} Let it be. Then you know. \end{thm}
Notes
External links
Labels and Cross-referencing
Another good point of LaTeX is that you can easily reference almost anything that is numbered (sections, figures, formulas), and LaTeX will take care of numbering, updating it whenever necessary. The commands to be used do not depend on what you are referencing, and they are:
\label{marker}- you give the object you want to reference a marker, you can see it like a name.
\ref{marker}- you can reference the object you have marked before. This prints the number that was assigned to the object
\pageref{marker}- It will print the number of the page where the object is.
LaTeX will calculate the right numbering for the objects in the document, the marker you have used to label the object will not be shown anywhere in the document. Then LaTeX will replace the string "\ref{marker}" with the right number that was assigned to the object. If you reference a marker that does not exist, the compilation of the document will be successful but LaTeX will return a warning:
LaTeX Warning: There were undefined references.
and it will replace "\ref{unknown-marker}" with "??" (so it will be easy to find in the document).
As you may have noticed reading how it works, it is a two-step process: first the compiler has to store the labels with the right number to be used for referencing, then it has to replace the \ref with the right number. That is why, when you use references, you have to compile your document twice to see the proper output. If you compile it only once, LaTeX will use the older information it collected in previous compilations (that might be outdated), but the compiler will inform you printing on the screen at the end of the compilation:
- LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.
Using the command \pageref{} you can help the reader to find the referenced object by providing also the page number where it can be found. You could write something like:
See figure~\ref{fig:test} on page~\pageref{fig:test}.
Since you can use exactly the same commands to reference almost anything, you might get a bit confused after you have introduced a lot of references. It is common practice among LaTeX users to add a few letters to the label to describe what you are referencing. Here is an example:
| chap: | chapter |
| sec: | section |
| fig: | figure |
| tab: | table |
| eq: | equation |
Following this convention, the label of a figure will look like \label{fig:my_figure}, etc. You are not obliged to use these prefixes. You can use any string as argument of \label{...}, but these prefixes become increasingly useful as your document grows in size.
Another suggestion: try to avoid using numbers within labels. You are better off describing what the object is about. This way, if you change the order of the objects, you will not have to rename all your labels and their references.
If you want to be able to see the markers you are using in the output document as well, you can use the showkeys package; this can be very useful while developing your document. For more information see the Packages section.
Examples
Here are some practical examples, but you will notice that they are all the same because they all use the same commands.
Sections
\section{Greetings} \label{sec:greetings} Hello! \section{Referencing} I greeted in section \ref{sec:greetings}. |
you could place the label anywhere in the section; anyway, in order to avoid confusion, it is better to place it immediately after the beginning of the section. Note how the marker starts with sec:, as suggested before. The label is then referenced in a different section.
Pictures
You can reference a picture by inserting it in the figure floating environment.
\begin{figure} \centering \includegraphics[width=0.5\textwidth]{gull} \caption{Close-up of a gull} \label{gull} \end{figure} Figure \ref{gull} shows a photograph of a gull. |
When a label is declared within a float environment, the \ref{...} will return the respective fig/table number, but it must occur after the caption. When declared outside, it will give the section number. To be completely safe, the label for any picture or table can go within the \caption{} command, as in
\caption{Close-up of a gull\label{gull}}
See the Floats, Figures and Captions section for more about the figure and related environments.
Fixing wrong labels
The command \label must appear after (or inside) \caption. Otherwise, it will pick up the current section or list number instead of what you intended.
\begin{figure} \begin{center} \includegraphics[width=0.5\textwidth]{gull} \caption{Close-up of a gull} \label{fig:gull} \end{center} \end{figure}
Issues with links to tables and figures handled by hyperref
In case you use the package hyperref to create a PDF, the links to tables or figures will point to the 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, it is above the pointer and one has to scroll up in order to see it. If you want the link point to the top of the image you can use the package hypcap [13] with:
\usepackage[all]{hypcap}
Be sure to call this package after the package hyperref, which should otherwise be loaded last.
Formulas
Here is an example showing how to reference formulas:
as you can see, the label is placed soon after the beginning 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 formulas, whether you are using amsmath or not. Note also the eq: prefix in the label.
eqref
The amsmath package adds a new command for referencing formulas; it is \eqref{}. It works exactly like \ref{}, but it adds brackets so that, instead of printing a plain number as 5, it will print (5). This can be useful to help the reader distinguish between formulas and other things, without the need to repeat the word "formula" before any reference. Its output can be changed as you wish; for more information see the amsmath documentation.
numberwithin
The amsmath package adds the \numberwithin{countera}{counterb} command which replaces the simple countera by a more sophisticated counterb.countera for example \numberwithin{equation}{section} in the preamble will append the section number to all equation numbers.
The varioref package
The varioref package introduces a new command called \vref{}. This command is used exactly like the basic \ref, but it has a different output according to the context. If the object to be referenced is in the same page, it works just like \ref; if the object is far away it will print something like "5 on page 25", i.e. it adds the page number automatically. If the object is close, it can use more refined sentences like "on the next page" or "on the facing page" automatically, according to the context and the document class.
This command has to be used very carefully. It outputs more than one word, so it may happen its output falls on two different pages. In this case, the algorithm can get confused and cause a loop. Let's make an example. You label an object on page 23 and the \vref output happens to stay between page 23 and 24. If it were on page 23, 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 are very hard to be fixed. You could think that this happens very rarely; unfortunately, if you write a long document you often edit with more than 100 references, situations like these are likely to happen. A possible way to avoid problems is to use the standard ref all the time, and convert it to vref when you are close to the final version of your document.
The hyperref package and \autoref{}
The hyperref package introduces another useful command; \autoref{}. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command \autoref{sec:intro} would create a hyperlink to the \label{sec:intro} command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining \typeautorefname to the prefix you want, as in:
\def\subsectionautorefname{section}
If you would like a hyperlink reference, but do not want the predefined text that \autoref{} provides, you can do this with a command such as \hyperref[sec:intro]{Appendix~\ref*{sec:intro}}. Note that you can disable the creation of hyperlinks in hyperref, and just use these commands for automatic text.
The hyperref package and \nameref{}
The hyperref package also automatically includes the nameref package, and a similarly named command. It is similar to \autoref{}, but inserts text corresponding to the section name, for example.
\section{MyFirstSection} \label{marker} \section{MySecondSection} In section \nameref{marker} we defined...
The hyperref package and \phantomsection
When you define a \label outside a figure, a table, or other floating objects, the label points to the current section. In some case, this behavior is not what you'd like and you'd prefer the generated link to point to the line where the \label is defined. This can be achieved with the command \phantomsection as in this example:
%The link location will be placed on the line below. \phantomsection \label{the_label}
References
Indexing
A useful feature of many books, index is an alphabetical list of words and expressions with the pages of the book upon which they are to be found. LaTeX supports the creation of indices with its package makeidx, and its support program makeindex, called on some systems makeidx.
Using makeidx
To enable the indexing feature of LaTeX, the makeidx package must be loaded in the preamble with:
\usepackage{makeidx}
and the special indexing commands must be enabled by putting the
\makeindex
command into the input file preamble. This should be done within the preamble, since it tells LaTeX to create the files needed for indexing. To tell LaTeX what to index, use
\index{key}
where key is the index entry and does not appear in the final layout. You enter the index commands at the points in the text that you want to be referenced in the index, likely near the reason for the key. For example, the text
To solve various problems in physics, it can be advantageous to express any arbitrary piecewise-smooth function as a Fourier Series composed of multiples of sine and cosine functions.
can be re-written as
To solve various problems in physics, it can be advantageous to express any arbitrary piecewise-smooth function as a Fourier Series \index{Fourier Series} composed of multiples of sine and cosine functions.
to cause an entry called 'Fourier Series' to appear with a reference to where ever the space between the words 'Fourier Series' and 'composed' appear.
To show the index within the document, merely use the command
\printindex
It is common to place it at the end of the document. The default index format is two columns.
The showidx package that comes with LaTeX prints out all index entries in the left margin of the text. This is quite useful for proofreading a document and verifying the index.
Compiling Indexes
When the input file is processed with LaTeX, each \index command writes an appropriate index entry, together with the current page number, to a special file. The file has the same name as the LaTeX input file, but a different extension (.idx). This .idx file can then be processed with the makeindex program. Type in the command line:
makeindex filename
Note that filename is without extension: the program will look for filename.idx and use that. You can optionally pass filename.idx directly to the program as an argument. The makeindex program generates a sorted index with the same base file name, but this time with the extension .ind. If now the LaTeX input file is processed again, this sorted index gets included into the document at the point where LaTeX finds \printindex.
The index created by latex with the default options may not look as nice or as suitable as you would like it. To improve the looks of the index makeindex comes with a set of style files, usually located somewhere in the tex directory structure, usually below the makeindex subdirectory. To tell makeindex to use a specific style file, run it with the command line option:
makeindex -s <style file> filename
If you use a GUI for compiling latex and index files, you may have to set this in the options. Here are some configuration tips for typical tools:
MakeIndex Settings in WinEdt
Say you want to add an index style file named simpleidx.ist
- Texify/PDFTexify: Options->Execution Modes->Accessories->PDFTeXify, add to the Switches:
--mkidx-option="-s simpleidx.ist" - MakeIndex alone: Options->Execution Modes->Accessories->MakeIndex, add to command line:
-s simpleidx.ist
Sophisticated Indexing
Below are examples of index entries:
Subentries
If some entry has subsections, these can be marked off with !. For example,
\index{encodings!input!cp850}
would an index with 'cp850' categorized under 'input' (which itself is categorized into 'encodings'). These are called subsubentries and subentries in makeidx terminology.
Controlling Sorting
In order to determine how an index key is sorted, place a value to sort by before the key with the @ as a separator. This is useful if there is any formatting or math mode, so one example may be
\index{F@$\vec{F}$}
so that the entry in the index will show as '
' but be sorted as 'F'.
Changing Page Number Style
To change the formatting of a page number, append a | and the name of some command which does the formatting. This command should only accept one argument.
For example, if on page 3 of a book you introduce bulldogs and include the command
\index{bulldog}
and on page 10 of the same book you wish to show the main section on bulldogs with a bold page number, use
\index{bulldog|textbf}
This will appear in the index as bulldog, 3, 10
Multiple Pages
To perform multi-page indexing, add a |( and |) to the end of the \index command, as in
\index{Quantum Mechanics!History|(} In 1901, Max Planck released his theory of radiation dependant on quantized energy. While this explained the ultraviolet catastrophe in the spectrum of blackbody radiation, this had far larger consequences as the beginnings of quantum mechanics. ... \index{Quantum Mechanics!History|)}
The entry in the index for the subentry 'History' will be the range of pages between the two \index commands.
Using special characters
In order to place values with !, @, or | in the \index command, one must quote these characters by using a double quotation mark (") and can only show " by quoting it (i.e., a key for " would be \index{""}).
This rule does not hold for \", so to put ȁ in the index, one may still use \index{a@\"{a}}
Warnings
Note that the \index command can affect your layout if not used carefully. Here is an example:
My Word \index{Word}. As opposed to Word\index{Word}. Note the position of the full stop. |
My Word . As opposed to Word. Note
the position of the full stop. |
Abbreviation list
You can make a list of abbreviations with the package nomencl [14].
To enable the Nomenclature feature of LaTeX, the nomencl package must be loaded in the preamble with:
\usepackage[⟨options ⟩]{nomencl} \makenomenclature
Issue the \nomenclature[⟨prefix ⟩]{⟨symbol ⟩}{⟨description ⟩} command for each symbol you want to have included in the nomenclature list. The best place for this command is immediately after you introduce the symbol for the first time. Put \printnomenclature at the place you want to have your nomenclature list.
Run LaTeX 2 times then
makeindex filename.nlo -s nomencl.ist -o filename.nls
followed by running LaTeX once again.
Multiple indexes
If you need multiple indexes you can use the package multind [15].
This package provides the same commands as makeidx, but now you also have to pass a name as the first argument to every command.
\usepackage{multind} \makeindex{books} \makeindex{authors} ... \index{books}{A book to index} \index{authors}{Put this author in the index} ... \printindex{books}{The Books index} \printindex{authors}{The Authors index}
Algorithms and Pseudocode
LaTeX has a variety of packages that can help to format algorithms, code, and "pseudocode". These packages provide stylistic enhancements over a uniform style (i.e., typewriter fonts) so that constructs such as loops or conditionals are visually separated from other text.
Typesetting Algorithms
Typesetting using the algorithmic package
The algorithmic environment provides a number of popular constructs for algorithm designs. The command \begin{algorithmic} can be given the optional argument of a positive integer, which if given will cause line numbering to occur at multiples of that integer. E.g. \begin{algorithmic}[5] will enter the algorithmic environment and number every fifth line.
Below is an example of typesetting a basic algorithm using the algorithmic package (remember to add the \usepackage{algorithmic} statement to your document preamble):
\begin{algorithmic} \IF {$i\geq maxval$} \STATE $i\gets 0$ \ELSE \IF {$i+k\leq maxval$} \STATE $i\gets i+k$ \ENDIF \ENDIF \end{algorithmic}
The LaTeX source can be written to a format familiar to programmers so that it is easy to read. This will not, however, affect the final layout in the document.
There are several constructs provided by algorithmic detailed below





































![\sqrt[n]{1+x+x^2+x^3+\ldots}
\,](http://upload.wikimedia.org/math/d/1/b/d1bddb178e5a3a629b0f364d2591642f.png)






















![() \, [] \, \{\} \, || \, \|\| \, \langle\rangle \, \lfloor\rfloor \, \lceil\rceil
\,](http://upload.wikimedia.org/math/d/7/a/d7a2a4ce921a29b9c7b255047d3394f1.png)




![[ \, ]](http://upload.wikimedia.org/math/3/b/1/3b12bb11542226fbabbed444e20f4110.png)





















































































and 
and 
and 
and 
,
and 
and 
and 
,
and 
and 
and 
and 
and 
and 
and 
,
and 
,
and 
,
and 
and 
and 
,
, and 
and 
and 
and 



































and 





