User:Dirk Hünniger/latex

From Wikibooks, open books for an open world
Jump to: navigation, search



What is TeX?[edit]

TeX is a low-level markup and programming language created by Donald Knuth to typeset documents attractively and consistently. 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. With the release of 8-bit character support in 1989, TeX development has been essentially frozen with only bug fixes released periodically. TeX is 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 do anything else but typesetting with it. The fine control TeX offers over document structure and formatting makes it a powerful—and formidable—tool. TeX is renowned for being extremely stable, for running on many different kinds of computers, and for being virtually bug free. The version numbers of TeX are converging toward , with a current version number of 3.1415926.

The name TeX is intended by its developer to be /'tɛx/, with the final consonant of loch or Bach. (Donald E. Knuth, The TeXbook) The letters of the name are meant to represent the capital Greek letters tau, epsilon, and chi, as TeX is an abbreviation of τέχνη (ΤΕΧΝΗ – technē), Greek for both "art" and "craft", which is also the root word of technical. English speakers often pronounce it /'tɛk/, like the first syllable of technical.

Programming in TeX generally progresses along a very gradual learning curve, requiring a significant investment of time to build custom macros for text formatting. Fortunately, document preparation systems based on TeX, consisting of collections of pre-built macros, do exist. These pre-built macros are time saving, and automate certain repetitive tasks and help reduce user introduced errors; however, this convenience comes at the cost of complete design flexibility. One of the most popular macro packages is called LaTeX.

What is LaTeX?[edit]

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. Within the typesetting system, its name is formatted as LaTeX.

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, which LaTeX reads to produce the final document.

This approach has some disadvantages in comparison with a WYSIWYG (What You See Is What You Get) program such as Writer or Microsoft Word.

In LaTeX:

  • You don't (usually) see the final version of the document when editing it.
  • You generally need to know the necessary commands for LaTeX markup.
  • It can sometimes be difficult to obtain a certain look for the document.

On the other hand, there are certain advantages to the LaTeX approach:

  • Document sources can be read with any text editor and understood, unlike the complex binary and XML formats used with WYSIWYG programs.
  • You can concentrate purely on the structure and contents of the document, not get caught up with superficial layout issues.
  • You don't need to manually adjust fonts, text sizes, line heights, or text flow for readability, as LaTeX takes care of them automatically.
  • In LaTeX the document structure is visible to the user, and can be easily copied to another document. In WYSIWYG applications it is often not obvious how a certain formatting was produced, and it might be impossible to copy it directly for use in another document.
  • The layout, fonts, tables and so on are consistent throughout the document.
  • Mathematical formulae can be easily typeset.
  • Indexes, footnotes, citations and references are generated easily.
  • Since the document source is plain text, tables, figures, equations, etc. can be generated programmatically with any language.
  • You are forced to structure your documents correctly.

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, JPEG, etc.

Philosophy of use[edit]

Flexibility and modularity[edit]

One of the most frustrating things beginners and even advanced users might encounter using LaTeX is the lack of flexibility regarding the document design and layout. If you want to design your document in a very specific way, you may have trouble accomplishing this. Keep in mind that LaTeX does the formatting for you, and mostly the right way. If it is not exactly what you desired, then the LaTeX way is at least not worse, if not better. One way to look at it is that LaTeX is a bundle of macros for TeX that aims to carry out everything regarding document formatting, so that the writer only needs to care about content. If you really want flexibility, use plain TeX instead.

One solution to this dilemma is to make use of the modular possibilities of LaTeX. You can build your own macros, or use macros developed by others. You are likely not the first person to face some particular formatting problem, and someone who encountered a similar problem before may have published their solution as a package.

CTAN is a good place to find many resources regarding TeX and derivative packages. It is the first place where you should begin searching.

Questions and documentation[edit]

Besides internet resources being plentiful, the best documentation source remains the official manual for every specific package, and the reference documentation, i.e., the TeXbook by D. Knuth and LaTeX: A document preparation system by L. Lamport.

Therefore before rushing on your favorite web search engine, we really urge you to have a look at the package documentation that causes troubles. This official documentation is most commonly installed along your TeX distribution, or may be found on CTAN.

Terms regarding TeX[edit]

Document preparation systems

LaTeX is a document preparation system based on TeX. So the system is the combination of the language and the macros.


TeX distributions are collections of packages and programs (compilers, fonts, and macro packages) that enable you to typeset without having to manually fetch files and configure things.


An engine is an executable that can turn your source code into a printable output format. The engine by itself only handles the syntax, it also needs to load fonts and macros to fully understand the source code and generate output properly. The engine will determine what kind of source code it can read, and what format it can output (usually DVI or PDF).

All in all, distributions are an easy way to install what you need to use the engines and the systems you want. Distributions usually target specific operating systems. You can use different systems on different engines, but sometimes there are restrictions. Code written for TeX, LaTeX or ConTeXt are (mostly) not compatible. Additionally, engine-specific code (like font for XeTeX) may not be compiled by every engine.

When searching for information on LaTeX, you might also stumble upon XeTeX, ConTeXt, LuaTeX or other names with a -TeX suffix. Let's recap most of the terms in this table.

Systems Descriptions
ConTeXt A TeX-based document preparation system (as LaTeX is) with a very consistent and easy syntax and support for pdfTeX, XeTeX and LuaTeX engines.

It does not have the same objective as LaTeX however.

LaTeX A TeX-based document preparation system designed by Leslie Lamport. It is actually a set of macros for TeX. It aims at taking care of the formatting process.
MetaFont A high-quality font system designed by Donald Knuth along TeX.
MetaPost A descriptive vector graphics language based on MetaFont.
TeX The original language designed by Donald Knuth.
Engines Descriptions
luatex, lualatex A TeX engine with Lua scripting engine embedded aiming at making TeX internals more flexible.
pdftex, pdflatex The engines (PDF compilers).
tex, latex The engines (DVI compilers).
xetex, xelatex a TeX engine which uses Unicode and supports widely popular .ttf and .otf fonts. See Fonts.
TeX Distributions Descriptions
MacTeX A TeX Live based distribution targetting Mac OS X.
MiKTeX A TeX distribution for Windows.
TeX Live A cross-platform TeX distribution.

What next?[edit]

In the next chapter we will proceed to the installation. Then we will compile our first LaTeX file.

Throughout this book you should also utilise other means for learning about LaTeX. Good sources are:


If this is the first time you are trying out LaTeX, you don't even need to install anything. For quick testing purpose you may just create a user account with an online LaTeX editor and continue this tutorial in the next chapter. These websites offer collaboration capabilities while allowing you to experiment with LaTeX syntax without having to bother with installing and configuring a distribution and an editor. When you later feel that you would benefit from having a standalone LaTeX installation, you can return to this chapter and follow the instructions below.

LaTeX is not a program by itself; it is a language. Using LaTeX requires a bunch of tools. Acquiring them manually would result in downloading and installing multiple programs in order to have a suitable computer system that can be used to create LaTeX output, such as PDFs. TeX Distributions help the user in this way, in that it is a single step installation process that provides (almost) everything.

At a minimum, you'll need a TeX distribution, a good text editor and a DVI or PDF viewer. More specifically, the basic requirement is to have a TeX compiler (which is used to generate output files from source), fonts, and the LaTeX macro set. Optional, and recommended installations include an attractive editor to write LaTeX source documents (this is probably where you will spend most of your time), and a bibliographic management program to manage references if you use them a lot.


TeX and LaTeX are available for most computer platforms, since they were programmed to be very portable. They are most commonly installed using a distribution, such as teTeX, MiKTeX, or MacTeX. TeX distributions are collections of packages and programs (compilers, fonts, and macro packages) that enable you to typeset without having to manually fetch files and configure things. LaTeX is just a set of macro packages built for TeX.

The recommended distributions for each of the major operating systems are:

  • TeX Live is a major TeX distribution for *BSD, GNU/Linux, Mac OS X and Windows.
  • MiKTeX is a Windows-specific distribution.
  • MacTeX is a Mac OS-specific distribution based on TeX Live.

These, however, do not necessarily include an editor. You might be interested in other programs that are not part of the distribution, which will help you in writing and preparing TeX and LaTeX files.

*BSD and GNU/Linux[edit]

In the past, the most common distribution used to be teTeX. As of May 2006 teTeX is no longer actively maintained and its former maintainer Thomas Esser recommended TeX Live as the replacement.[1]

The easy way to get TeX Live is to use the package manager or portage tree coming with your operating system. Usually it comes as several packages, with some of them being essential, other optional. The core TeX Live packages should be around 200-300 MB.

If your *BSD or GNU/Linux distribution does not have the TeX Live packages, you should report a wish to the bug tracking system. In that case you will need to download TeX Live yourself and run the installer by hand.

You may wish to install the content of TeX Live more selectively. See below.

Mac OS X[edit]

Mac OS X users may use MacTeX, a TeX Live-based distribution supporting TeX, LaTeX, AMSTeX, ConTeXt, XeTeX and many other core packages. Download MacTeX.pkg on the MacTeX page, unzip it and follow the instructions. Further information for Mac OS X users can be found on the TeX on Mac OS X Wiki.

Since Mac OS X is also a Unix-based system, TeX Live is naturally available through MacPorts and Fink. Homebrew users should use the official MacTeX installer because of the unique directory structure used by TeX Live. Further information for Mac OS X users can be found on the TeX on Mac OS X Wiki.

Microsoft Windows[edit]

Microsoft Windows users can install MiKTeX onto their computer. It has an easy installer that takes care of setting up the environment and downloading core packages. This distribution has advanced features, such as automatic installation of packages, and simple interfaces to modify settings, such as default paper sizes.

There is also a port of TeX Live available for Windows.

Custom installation with TeX Live[edit]

This section targets users who want fine-grained control over their TeX distribution, like an installation with a minimum of disk space usage. If it is none of your concern, you may want to jump to the next section.

Picky users may wish to have more control over their installation. Common distributions might be tedious for the user caring about disk space. In fact, MikTeX and MacTeX and packaged TeX Live features hundreds of LaTeX packages, most of them which you will never use. Most Unix with a package manager will offer TeX Live as a set of several big packages, and you often have to install 300–400 MB for a functional system.

TeX Live features a manual installation with a lot of possible customizations. You can get the network installer at This installer allows you to select precisely the packages you want to install. As a result, you may have everything you need for less than 100 MB. TeX Live is then managed through its own package manager, tlmgr. It will let you configure the distributions, install or remove extra packages and so on.

You will need a Unix-based operating system for the following. Mac OS X, GNU/Linux or *BSD are fine. It may work for Windows but the process must be quite different.

TeX Live groups features and packages into different concepts:

  • Collections are groups of packages that can always be installed individually, except for the Essential programs and files collection. You can install collections at any time.
  • Installation Schemes group collections and packages. Schemes can only be used at installation time. You can select only one scheme at a time.

Minimal installation[edit]

We will give you general guidelines to install a minimal TeX distribution (i.e., only for plain TeX).

  1. Download the installer at and extract it to a temporary folder.
  2. Open a terminal in the extracted folder and log in as root.
  3. Change the umask permissions to 022 (user read/write/execute, group/others read/execute only) to make sure other users will have read-only access to the installed distribution.
# umask 022
  1. Launch install-tl.
  2. Select the minimal scheme (plain only).
  3. You may want to change the directory options. For example you may want to hide your personal macro folder which is located at TEXMFHOME. It is ~/texmf by default. Replace it by ~/.texmf to hide it.
  4. Now the options:
    1. use letter size instead of A4 by default: mostly for users from the USA.
    2. execution of restricted list of programs: it is recommended to select it for security reasons. Otherwise it allows the TeX engines to call any external program. You may still configure the list afterwards.
    3. create format files: targetting a minimal disk space, the best choice depends on whether there is only one user on the system, then deselecting it is better, otherwise select it. From the help menu: "If this option is set, format files are created for system-wide use by the installer. Otherwise they will be created automatically when needed. In the latter case format files are stored in user's directory trees and in some cases have to be re-created when new packages are installed."
    4. install font/macro doc tree: useful if you are a developer, but very space consuming. Turn it off if you want to save space.
    5. install font/macro source tree: same as above.
    6. Symlinks are fine by default, change it if you know what you are doing.
  5. Select portable installation if you install the distribution to an optical disc, or any kind of external media. Leave to default for a traditional installation on the system hard drive.

At this point it should display

1 collections out of 85, disk space required: 40 MB

or a similar space usage.

You can now proceed to installation: start installation to hard disk.

Don't forget to add the binaries to your PATH as it's noticed at the end of the installation procedure.

First test[edit]

In a terminal write

$ tex '\empty Hello world!\bye'
$ pdftex '\empty Hello world!\bye'

You should get a DVI or a PDF file accordingly.


Formerly, TeX distributions used to be configured with the texconfig tool from the teTeX distribution. TeX Live still features this tool, but recommends using its own tool instead: tlmgr. Note that as of January 2013 not all texconfig features are implemented by tlmgr. Only use texconfig when you cannot do what you want with tlmgr.

List current installation options:

tlmgr option

You can change the install options:

tlmgr option srcfiles 1
tlmgr option docfiles 0
tlmgr paper letter

See the TLMGR(1) man page for more details on its usage. If you did not install the documents as told previously, you can still access the tlmgr man page with

tlmgr help

Installing LaTeX[edit]

Now we have a running plain TeX environment, let's install the base packages for LaTeX.

# tlmgr install latex latex-bin latexconfig latex-fonts

In this case you can omit latexconfig latex-fonts as they are auto-resolved dependencies to LaTeX. Note that tlmgr resolves some dependencies, but not all. You may need to install dependencies manually. Thankfully this is rarely too cumbersome.

Other interesting packages:

# tlmgr install amsmath babel carlisle ec geometry graphics hyperref lm  marvosym oberdiek parskip graphics-def url
amsmath The essentials for math typesetting.
babel Internationalization support.
carlisle Bundle package required for some babel features.
ec Required for T1 encoding.
geometry For page layout.
graphics The essentials to import graphics.
hyperref PDF bookmarks, PDF followable links, link style, TOC links, etc.
lm One of the best Computer Modern style font available for several font encodings (such as T1).
marvosym Several symbols, such as the official euro.
oberdiek Bundle package required for some geometry features.
parskip Let you configure paragraph breaks and indents properly.
graphics-def Required for some graphics features.
url Required for some hyperref features.

If you installed a package you do not need anymore, use

# tlmgr remove <package>


If you are using Babel for non-English documents, you need to install the hyphenation patterns for every language you are going to use. They are all packaged individually. For instance, use

# tlmgr install hyphen-{finnish,sanskrit}

for finnish and sanskrit hyphenation patterns.

Note that if you have been using another TeX distribution beforehand, you may still have hyphenation cache stored in you home folder. You need to remove it so that the new packages are taken into account. The TeX Live cache is usually stored in the ~/.texliveYYYY folder (YYYY stands for the year). You may safely remove this folder as it contains only generated data. TeX compilers will re-generate the cache accordingly on next compilation.


By default TeX Live will install in /usr/local/texlive. The distribution is quite proper as it will not write any file outside its folder, except for the cache (like font cache, hyphenation patters, etc.). By default,

  • the system cache goes in /var/lib/texmf;
  • the user cache goes in ~/.texliveYYYY.

Therefore TeX Live can be installed and uninstalled safely by removing the aforementioned folders.

Still, TeX Live provides a more convenient way to do this:

# tlmgr uninstall

You may still have to wipe out the folders if you put untracked files in them.


TeX and LaTeX source documents (as well as related files) are all text files, and can be opened and modified in almost any text editor. You should use a text editor (e.g. Notepad), not a word processor (Word, OpenOffice). Dedicated LaTeX editors are more useful than generic plain text editors, because they usually have autocompletion of commands, spell and error checking and handy macros.


BaKoMa TeX[edit]

BaKoMa TeX is an editor for Windows and Mac OS with WYSIWYG-like features. It takes care of compiling the LaTeX source and updating it constantly to view changes to document almost in real time. You can take an evaluation copy for 28 days.


Emacs is a general purpose, extensible text processing system. Advanced users can program it (in elisp) to make Emacs the best LaTeX environment that will fit their needs. In turn beginners may prefer using it in combination with AUCTeX and Reftex (extensions that may be installed into the Emacs program). Depending on your configuration, Emacs can provide a complete LaTeX editing environment with auto-completion, spell-checking, a complete set of keyboard shortcuts, table of contents view, document preview and many other features.


Gedit with gedit-latex-plugin is also worth trying out for users of GNOME. GEdit is a cross-platform application for Windows, Mac, and Linux


Screenshot of Gummi.

Gummi is a LaTeX editor for Linux, which compiles the output of pdflatex in realtime and shows it on the right half of the screen[2].



LyX is a popular document preparation system for Windows, Linux and Mac OS. It provides a graphical interface to LaTeX, including several popular packages. It contains formula and table editors and shows visual clues of the final document on the screen enabling users to write LaTeX documents without worrying about the actual syntax. LyX calls this a What You See Is What You Mean (WYSIWYM) approach.[3]

LyX saves its documents in their own markup, and generates LaTeX code based on this. The user is mostly isolated from the LaTeX code and not in complete control of it, and as such LyX is not a normal LaTeX editor. However, as LaTeX is underlying system, knowledge of how that works is useful also for a LyX user. In addition, if one wants to do something that is not supported in the GUI, using LaTeX code may be required.


TeXmaker is a cross-platform editor very similar to Kile in features and user interface. In addition it has its own PDF viewer.


TeXstudio is a cross-platform open source LaTeX editor forked from Texmaker.


Screenshot of TeXworks on Ubuntu 12.10.

TeXworks is a dedicated TeX editor that is included in MiKTeX and TeX Live. It was developed with the idea that a simple interface is better than a cluttered one, and thus to make it easier for people in their early days with LaTeX to get to what they want to do: write their documents. TeXworks originally came about precisely because a math professor wanted his students to have a better initial experience with LaTeX.

You can install TeXworks with the package manager of your Linux distribution or choose it as an install option in the Windows or Mac installer.


Vim is another general purpose text editor for a wide variety of platforms including UNIX, Mac OS X and Windows. A variety of extensions exist including LaTeX Box and Vim-LaTeX.

*BSD and GNU/Linux-only[edit]


Screenshot of Kile.

Kile is a LaTeX editor for KDE (cross platform), providing a powerful GUI for editing multiple documents and compiling them with many different TeX compilers. Kile is based on Kate editor, has a quick access toolbar for symbols, document structure viewer, a console and customizable build options. Kile can be run in all operating systems that can run KDE.


LaTeXila is another text editor for Linux (Gnome).

Mac OS X-only[edit]


TeXShop, the model for the TeXworks editor and previewer, is for Mac OS and is bundled with the MacTeX distribution. It uses multiple windows, one for editing the source, one for the preview, and one as a console for error messages. It offers one-click updating of the preview and allows easy crossfinding between the code and the preview by using CMD-click along with many features to make editing and typesetting TeX source easier.


TeXnicle is a free editor for Mac OS that includes the ability to perform live updates. It includes a code library for the swift insertion of code and the ability to execute detailed word counts on documents. It also performs code highlighting and the editing window is customisable, permitting the user to select the font, colour, background colour of the editing environment. It is in active development.


Archimedes is an easy-to-use LaTeX and Markdown editor designed from the ground up for Mac OS X. It includes a built-in LaTeX library, code completion support, live previews, macro support, integration with sharing services, and PDF and HTML export options. Archimedes's Magic Type feature lets users insert mathematical symbols just by drawing them on their MacBook's trackpad or Magic Trackpad.


Texpad is an integrated editor and viewer for Mac OS with a companion app for iOS devices. Similar to TeXShop, Texpad requires a working MacTeX distribution to function, however it can also support other distributions side-by-side with MacTex. It offers numerous features including templates, outline viewing, auto-completion, spell checking, customizable syntax highlighting, to-do list integration, code snippets, Markdown integration, multi-lingual support, and a Mac OS native user interface. Although Texpad offers a free evaluation period, the unlocked version is a paid download.





TeXnicCenter is a popular free and open source LaTeX editor for Windows. It also has a similar user interface to TeXmaker and Kile.


WinEdt is a powerful and versatile text editor with strong predisposition towards creation of LaTeX/TeX documents for Windows. It has been designed and configured to integrate with TeX Systems such as MiTeX or TeX Live. Its built-in macro helps in compiling the LaTeX source to the WYSIWYG-like DVI or PDF or PS and also in exporting the document to other mark-up languages as HTML or XML.



Online solutions[edit]

To get started without needing to install anything, you can use a web-hosted service featuring a full TeX distribution and a web LaTeX editor.

  • Authorea is an integrated online framework for the creation of technical documents in collaboration. Authorea's frontend allows you to enter text in LaTeX or Markdown, as well as figures, and equations (in LaTeX or MathML). Authorea's versioning control system is entirely based on Git (every article is a Git repository).
  • Overleaf is a secure, easy to use online LaTeX editor with integrated rapid preview - like EtherPad for LaTeX. Start writing with one click (no signup required) and share the link. It supports real time preview, figures, bibliographies and custom styles.
  • is a secure cloud-based LaTeX editor offering unlimited free projects. Premium accounts are available for extra features such as collaborative editing, version control and Dropbox integration.
  • SimpleLaTeX is an online editor and previewer for short LaTeX notes, which can be optionally cached or shared. Previews are available in SVG, PNG, and PDF. It also includes a simple GUI for editing tables.
  • Verbosus is a professional Online LaTeX Editor that supports collaboration with other users and is free to use. Merge conflicts can easily resolved by using a built-in merge tool that uses an implementation of the diff-algorithm to generate information required for a successful merge.

Bibliography management[edit]

Bibliography files (*.bib) are most easily edited and modified using a management system. These graphical user interfaces all feature a database form, where information is entered for each reference item, and the resulting text file can be used directly by BibTeX.


Screenshot of JabRef.

Mac OS X-only[edit]

Screenshot of BibDesk
  • BibDesk is a bibliography manager based on a BibTeX file. It imports references from the internet and makes it easy to organize references using tags and categories[4].


Finally, you will need a viewer for the files LaTeX outputs. Normally LaTeX saves the final document as a .dvi (Device independent file format), but you will rarely want it to. DVI files do not contain embedded fonts and many document viewers are unable to open them.

Usually you will use a LaTeX compiler like pdflatex to produce a PDF file directly, or a tool like dvi2pdf to convert the DVI file to PDF format. Then you can view the result with any PDF viewer.

Practically all LaTeX distributions have a DVI viewer for viewing the default output of latex, and also tools such as dvi2pdf for converting the result automatically to PDF and PS formats.

Here follows a list of various PDF viewers.

Tables and graphics tools[edit]

LaTeX is a document preparation system, it does not aim at being a spreadsheet tool nor a vector graphics tool.

If LaTeX can render beautiful tables in a dynamic and flexible manner, it will not handle the handy features you could get with a spreadsheet like dynamic cells and calculus. Other tools are better at that. The ideal solution is to combine the strength of both tools: build your dynamic table with a spreadsheet, and export it to LaTeX to get a beautiful table seamlessly integrated to your document. See Tables for more details.

The graphics topic is a bit different since it is possible to write procedural graphics from within your LaTeX document. Procedural graphics produce state-of-the-art results that integrates perfectly to LaTeX (e.g. no font change), but have a steep learning curve and require a lot of time to draw.

For easier and quicker drawings, you may want to use a WYSIWYG tool and export the result to a vector format like PDF. The drawback is that it will contrast in style with the rest of your document (font, size, etc.). Some tools have the capability to export to LaTeX, which will partially solve this issue. See Importing Graphics for more details.


  1. teTeX Home Page (Retrieved January 31, 2007)
  2. Gummi
  3. LyX
  4. BibDesk

Installing Extra Packages[edit]

Add-on features for LaTeX are known as packages. Dozens of these are pre-installed with LaTeX and can be used in your documents immediately. They should all be stored in subdirectories of texmf/tex/latex named after each package. The directory name "texmf" stands for “TEX and METAFONT”. To find out what other packages are available and what they do, you should use the CTAN search page which includes a link to Graham Williams' comprehensive package catalogue.

A package is a file or collection of files containing extra LaTeX commands and programming which add new styling features or modify those already existing. There are two main file types: class files with .cls extension, and style files with .sty extension. There may be ancillary files as well. When you try to typeset a document which requires a package which is not installed on your system, LaTeX will warn you with an error message that it is missing. You can download updates to packages you already have (both the ones that were installed along with your version of LaTeX as well as ones you added). There is no limit to the number of packages you can have installed on your computer (apart from disk space!), but there is a configurable limit to the number that can be used inside any one LaTeX document at the same time, although it depends on how big each package is. In practice there is no problem in having even a couple of dozen packages active.

Most LaTeX installations come with a large set of pre-installed style packages, so you can use the package manager of the TeX distribution or the one on your system to manage them. See the automatic installation. But many more are available on the net. The main place to look for style packages on the Internet is CTAN. Once you have identified a package you need that is not in your distribution, use the indexes on any CTAN server to find the package you need and the directory where it can be downloaded from. See the manual installation.

Automatic installation[edit]

If on an operating system with a package manager or a portage tree, you can often find packages in repositories.

With MikTeX there is a package manager that allows you to pick the package you want individually. As a convenient feature, upon the compilation of a file requiring non-installed packages, MikTeX will automatically prompt to install the missing ones.

With TeX Live, it is common to have the distribution packed into a few big packages. For example, to install something related to internationalization, you might have to install a package like texlive-lang. With TeX Live manually installed, use tlmgr to manage packages individually.

tlmgr install <package1> <package2> ...
tlmgr remove <package1> <package2> ...

The use of tlmgr is covered in the Installation chapter.

If you cannot find the wanted package with any of the previous methods, see the manual installation.

Manual installation[edit]

Downloading packages[edit]

What you need to look for is usually two files, one ending in .dtx and the other in .ins. The first is a DOCTeX file, which combines the package program and its documentation in a single file. The second is the installation routine (much smaller). You must always download both files. If the two files are not there, it means one of two things:

  • Either the package is part of a much larger bundle which you shouldn't normally update unless you change User:Dirk Hünnigerversion of LaTeX;
  • or it's an older or relatively simple package written by an author who did not use a .dtx file.

Download the package files to a temporary directory. There will often be a readme.txt with a brief description of the package. You should of course read this file first.

Installing a package[edit]

There are five steps to installing a LaTeX package. (These steps can also be used on the pieces of a complicated package you wrote yourself; in this case, skip straight to Step 3.)

1. Extract the files Run LaTeX on the .ins file. That is, open the file in your editor and process it as if it were a LaTeX document (which it is), or if you prefer, type latex followed by the .ins filename in a command window in your temporary directory. This will extract all the files needed from the .dtx file (which is why you must have both of them present in the temporary directory). Note down or print the names of the files created if there are a lot of them (read the log file if you want to see their names again).

2. Create the documentation Run LaTeX on the .dtx file. You might need to run it twice or more, to get the cross-references right (just like any other LaTeX document). This will create a .dvi file of documentation explaining what the package is for and how to use it. If you prefer to create PDF then run pdfLaTeX instead. If you created a .idx as well, it means that the document contains an index, too. If you want the index to be created properly, follow the steps in the indexing section. Sometimes you will see that a .glo (glossary) file has been produced. Run the following command instead:

makeindex -s -o name.gls name.glo

3. Install the files While the documentation is printing, move or copy the package files from your temporary directory to the right place[s] in your TeX local installation directory tree. Packages installed by hand should always be placed in your "local" directory tree, not in the directory tree containing all the pre-installed packages. This is done to a) prevent your new package accidentally overwriting files in the main TeX directories; and b) avoid your newly-installed files being overwritten when you next update your version of TeX.

For a TDS(TeX Directory Structure)-conformant system, your "local installation directory tree" is a folder and its subfolders. The outermost folder should probably be called texmf-local/ or texmf/. Its location depends on your system:

The "right place" sometimes causes confusion, especially if your TeX installation is old or does not conform to the TeX Directory Structure(TDS). For a TDS-conformant system, the "right place" for a LaTeX .sty file is a suitably-named subdirectory of texmf/tex/latex/. "Suitably-named" means sensible and meaningful (and probably short). For a package like paralist, for example, I'd call the directory texmf/tex/latex/paralist.

Often there is just a .sty file to move, but in the case of complex packages there may be more, and they may belong in different locations. For example, new BibTeX packages or font packages will typically have several files to install. This is why it is a good idea to create a sub-directory for the package rather than dump the files into misc along with other unrelated stuff. If there are configuration or other files, read the documentation to find out if there is a special or preferred location to move them to.

Where to put files from packages
Type Directory (under texmf/ or texmf-local/) Description
.afm fonts/afm/foundry/typeface Adobe Font Metrics for Type 1 fonts
.bib bibtex/bib/bibliography BibTeX bibliography
.bst bibtex/bst/packagename BibTeX style
.cls tex/latex/base Document class file
.dvi doc package documentation
.enc fonts/enc Font encoding
.fd tex/latex/mfnfss Font Definition files for METAFONT fonts
.fd tex/latex/psnfss Font Definition files for PostScript Type 1 fonts
.map fonts/map Font mapping files
.mf fonts/source/public/typeface METAFONT outline
.pdf doc package documentation
.pfb fonts/type1/foundry/typeface PostScript Type 1 outline
.sty tex/latex/packagename Style file: the normal package content
.tex doc TeX source for package documentation
.tex tex/plain/packagename Plain TeX macro files
.tfm fonts/tfm/foundry/typeface TeX Font Metrics for METAFONT and Type 1 fonts
.ttf fonts/truetype/foundry/typeface TrueType font
.vf fonts/vf/foundry/typeface TeX virtual fonts
others tex/latex/packagename other types of file unless instructed otherwise

For most fonts on CTAN, the foundry is public.

4. Update your index Finally, run your TeX indexer program to update the package database. This program comes with every modern version of TeX and has various names depending on the LaTeX distribution you use. (Read the documentation that came with your installation to find out which it is, or consult

  • teTeX, TeX Live, fpTeX: texhash
  • web2c: mktexlsr
  • MacTeX: MacTeX appears to do this for you.
  • MikTeX: initexmf --update-fndb (or use the GUI)
  • MiKTeX 2.7 or later versions, installed on Windows XP through Windows 7: Start -> All Programs -> MikTex -> Settings. In Windows 8 use the keyword Settings and choose the option of Settings with the MiKTex logo. In Settings menu choose the first tab and click on Refresh FNDB-button (MikTex will then check the Program Files directory and update the list of File Name DataBase). After that just verify by clicking 'OK'.

5. Update font maps If your package installed any TrueType or Type 1 fonts, you need to update the font mapping files in addition to updating the index. Your package author should have included a .map file for the fonts. The map updating program is usually some variant on updmap, depending on your distribution:

  • TeX Live and MacTeX: updmap --enable (if you installed the files in a personal tree) or updmap-sys --enable (if you installed the files in a system directory).
  • MikTeX: Run initexmf --edit-config-file updmap, add the line "Map to the file that opens, then run initexmf --mkmaps.


The reason this process has not been automated widely is that there are still thousands of installations which do not conform to the TDS, such as old shared Unix systems and some Microsoft Windows systems, so there is no way for an installation program to guess where to put the files: you have to know this. There are also systems where the owner, user, or installer has chosen not to follow the recommended TDS directory structure, or is unable to do so for political or security reasons (such as a shared system where the user cannot write to a protected directory). The reason for having the texmf-local directory (called texmf.local on some systems) is to provide a place for local modifications or personal updates, especially if you are a user on a shared or managed system (Unix, Linux, VMS, Windows NT/2000/XP, etc.) where you may not have write-access to the main TeX installation directory tree. You can also have a personal texmf subdirectory in your own login directory. Your installation must be configured to look in these directories first, however, so that any updates to standard packages will be found there before the superseded copies in the main texmf tree. All modern TeX installations should do this anyway, but if not, you can edit texmf/web2c/texmf.cnf yourself.

Checking package status[edit]

The universal way to check if a file is available to TeX compilers is the command-line tool kpsewhich.

$ kpsewhich tikz

kpsewhich will actually search for files only, not for packages. It returns the path to the file. For more details on a specific package use the command-line tool tlmgr (TeX Live only):

tlmgr info <package>

The tlmgr tool has lot more options. To consult the documentation:

tlmgr help

Package documentation[edit]

To find out what commands a package provides (and thus how to use it), you need to read the documentation. In the texmf/doc subdirectory of your installation there should be directories full of .dvi files, one for every package installed. This location is distribution-specific, but is typically found in:

Distribution Path
MacTeX /Library/TeX/Documentation/texmf-doc/latex
MiKTeX %MIKTEX_DIR%\doc\latex
TeX Live $TEXMFDIST/doc/latex

Generally, most of the packages are in the latex subdirectory, although other packages (such as BibTeX and font packages) are found in other subdirectories in doc. The documentation directories have the same name of the package (e.g. amsmath), which generally have one or more relevant documents in a variety of formats (dvi, txt, pdf, etc.). The documents generally have the same name as the package, but there are exceptions (for example, the documentation for amsmath is found at latex/amsmath/amsdoc.dvi). If your installation procedure has not installed the documentation, the DVI files can all be downloaded from CTAN. Before using a package, you should read the documentation carefully, especially the subsection usually called "User Interface", which describes the commands the package makes available. You cannot just guess and hope it will work: you have to read it and find out.

You can usually automatically open any installed package documentation with the texdoc command:

texdoc <package-name>

External resources[edit]

The best way to look for LaTeX packages is the already mentioned CTAN: Search. Additional resources form The TeX Catalogue Online:

See Also[edit]


This tutorial is aimed at getting familiar with the bare bones of LaTeX.

Before starting, ensure you have LaTeX installed on your computer (see Installation for instructions of what you will need).

  • We will first have a look at the LaTeX syntax.
  • We will create our first LaTeX document.
  • Then we will take you through how to feed this file through the LaTeX system to produce quality output, such as postscript or PDF.
  • Finally we will have a look at the file names and types.

The LaTeX syntax[edit]

LaTeX uses a markup language in order to describe document structure and presentation. LaTeX converts 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 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.

A minimal example looks something like the following (the commands will be explained later):


Hello world!


The LaTeX compiler normalises whitespace so that whitespace characters, such as [space] or [tab], are treated uniformly as "space": several consecutive "spaces" are treated as one, "space" opening a line is generally ignored, and a single line break also yields “space”. A double line break (an empty line), however, defines the end of a paragraph; multiple empty lines are also treated as the end of a paragraph. An example of applying these rules is presented below: the left-hand side shows the user's input (.tex), while the right-hand side depicts the rendered output (.dvi/.pdf/.ps).

It does not matter whether you
enter one or several             spaces
after a word.

An empty line starts a new

It does not matter whether you enter one or several spaces after a word.

An empty line starts a new paragraph.

Reserved Characters[edit]

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{}

In some circumstances, the bracket characters [ and ] can also be considered as reserved characters, as they are used to give optional parameters to some commands. If you want to print these directly after some command, like in this situation: \command [text] it will fail, as [text] will be considered as an option given to \command. You can achieve the correct output this way: \command {} [text].

The backslash character \ cannot 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 commands \~ and \^ produce respectively a tilde and a hat which is placed over the next letter. For example \~n gives ñ. That's why you need braces to specify there is no letter as argument. You can also use \textasciitilde and \textasciicircum to enter these characters; or other commands .

If you want to insert text that might contain several particular symbols (such as URIs), you can consider using the \verb command, which will be discussed later in the section on formatting. For source code, see Source Code Listings

The 'less than' (<) and 'greater than' (>) characters are the only visible ASCII characters (not reserved) that will not print correctly. See Special Characters for an explanation and a workaround.

Non-ASCII characters (e.g. accents, diacritics) can be typed in directly for most cases. However you must configure the document appropriately. The other symbols and many more can be printed with special commands as in mathematical formulae or as accents. We will tackle this issue in Special Characters.

LaTeX groups[edit]

Sometimes a certain state shall be kept local, i.e. limiting its scope. This can be done by enclosing the part to be changed locally in curly braces. In certain occasions, using braces won't be possible. LaTeX provides \bgroup and \egroup to begin and end a group, respectively.

normal text {\itshape walzing \bfseries Wombat} more normal text

normal text \bgroup\itshape walzing \bfseries Wombat\egroup{} more normal text

Environments form an implicit group.

LaTeX environments[edit]

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:

text to be influenced

Between the \begin and the \end you can put other commands and nested environments. The internal mechanism of environments defines a group, which makes its usage safe (no influence on the other parts of the document). 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.

LaTeX commands[edit]

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 an argument, 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:


Most standard LaTeX commands have a switch equivalent. Switches have no arguments but apply on the rest of the scope, i.e. the current group or environment. A switch should (almost) never be called outside of any scope, otherwise it will apply on the rest of the document.


% \emph is a command with argument, \em is a switch.
\emph{emphasized text}, this part is normal % Correct
{\em emphasized text}, this part is normal % Correct

\em emphasized text, this part is normal % Incorrect
\em{emphasized text}, this part is normal % Incorrect


When LaTeX encounters a % character while processing an input file, it ignores the rest of the current 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%

This is an example: Supercalifragilisticexpialidocious

Note that the % character can be used to split long input lines that do not allow whitespace or line breaks, as with Supercalifragilisticexpialidocious above.

The core LaTeX language does not have a predefined syntax for commenting out regions spanning multiple lines. Refer to multiline comments for simple workarounds.

Our first document[edit]

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 favorite text-editor. vim, emacs, Notepad++, and other text editors will 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!
Hello World!
  • Save your file as hello.tex.

When picking a name for your file, make sure it bears a .tex extension.

What does it all mean?[edit]

% 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 people 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 begins 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, provided there is no white space before the percent sign.


Compilation process[edit]

The general concept is to transform a plain text document into a publishable format, mostly a DVI, PS or PDF file. This process is called compilation, which is done by an executable file called a compiler.

There are two main compilers.

  • tex compiler reads a TeX .tex file and creates a .dvi.
  • pdftex compiler reads a TeX .tex file and creates a .pdf.

These compilers are basically used to compile Plain TeX, not LaTeX. There is no such LaTeX compiler since LaTeX is just a bunch of macros for TeX. However, there are two executables related to the previous compilers:

  • latex executable calls tex with LaTeX initialization files, reads a LaTeX .tex file and creates a .dvi
  • pdflatex executable calls pdftex with LaTeX initialization files, reads a LaTeX .tex file and creates a .pdf

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 many errors.

As a matter of fact, following your operating system latex and pdflatex are simple scripts or symbolic links.

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. Here are common programs you expect to find in any LaTeX distribution:

  • dvi2ps converts the .dvi file to .ps (postscript).
  • dvi2pdf converts the .dvi file to .pdf (dvi2pdfm is an improved version).

and with Ghostscript:

  • ps2pdf and pdf2ps converts the .ps file to .pdf and vice-versa.

When LaTeX was created, the only format it could create was DVI; later PDF support was added by pdflatex. PDF files can be created with both pdflatex and dvipdfm. The output of pdflatex takes direct advantage of modern features of PDF such as hyperlinks and embedded fonts, which are not part of DVI. Passing through DVI imposes limitations of its older format. On the other hand, some packages, such as PSTricks, exploit the process of conversion to DVI, and therefore will not work with pdflatex. Some of those packages embed information in the DVI that doesn't appear when the DVI is viewed, but reemerges when the DVI is converted to another, newer format.

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, while the compiler can handle the translation itself.

The following diagram shows the relationships between the LaTeX source code and the formats you can create from it:

LaTeX diagram.svg

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 features of your document. Therefore, 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.

Chapter Export To Other Formats discusses more about exporting LaTeX source to other file formats.

Generating the document[edit]

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. 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 you already have a working LaTeX installation on your computer.

  1. Type the command: latex hello (the .tex extension is not required, although you can include it if you wish)
  2. 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. 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). (Now evince and okular, the standard document viewers for many Linux distributions are able to view DVI files.)

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:

  1. Type the command: pdflatex hello (as before, the .tex extension is not required)
  2. 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. It also supports advanced typographic features: hanging punctuation, font expansion and margin kerning resulting in more flexibility available to the TeX engine and better looking output. 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, but for 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.

Autobuild Systems[edit]

Compiling using only the latex binary can be quite tricky as soon as you start working on more complex documents as previously stated. A number of programs exist to automatically read in a TeX document and run the appropriate compilers the appropriate number of times. For example, latexmk can generate a PDF from most TeX files simply:

$ latexmk -pdf file.tex

Note that most editors will take care of it for you.

Compressed PDF[edit]

For a PDF output, you may have noticed that the output PDF file is not always the same size depending on the engine you used to compile the file. So latex → dvips → ps2pdf will usually be much smaller than pdflatex. If you want pdflatex features along with a small output file size, you can use the Ghostscript command:

$ gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="Compressed.pdf" "Original.pdf"


Picking suitable filenames[edit]

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 only one full point or period (.) to separate the file extension (somewhat similar to the conventions for a good 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.

Ancillary files[edit]

The TeX compilers are single-pass processes. It means that there is no way for a compiler to jump around the document, which would be useful for the table of contents and references. Indeed the compiler cannot guess at which page a specific section is going to be printed, so when the table of contents is printed before the upcoming sections, it cannot set the page numbers.

To circumvent this issue, many LaTeX commands which need to jump use ancillary files which usually have the same file name as the current document but a different extension. It stores temporary data into these files and use them for the next compilation. So to have an up-to-date table of contents, you need to compile the document twice. There is no need to re-compile if no section moved.

For example, the temporary file for the table of contents data is filename.toc.

None of these files contains unrecoverable information. It means you can delete them safely, compiling will regenerate them automatically.

When you work with various capabilities of LaTeX (index, glossaries, bibliographies, etc.) 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:

Common file extensions in LaTeX
.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. (where you can store a list of full bibliographic citations)
.blg BiBTeX log file. (errors are logged here)
.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.
.pdf 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.
.out hyperref package file, just one for the master file.

And what now?[edit]

Common Elements[edit]

See Document Structure and the Common Elements part for all the common features that belong to every type of document.

Non-English documents and special characters[edit]

LaTeX has some nice features for most languages in the world. You can tell LaTeX to follow typography rules of the target language, ease special characters input, and so on. See Special Characters and Internationalization.

Modular document[edit]

See Modular Documents for good recommendations about the way to organize big projects into multiple files.

Questions and Issues[edit]

We highly urge you to read the FAQ if you have issues about basic features, or if you want to read essential recommendations. For the more specific questions and issues, refer to the Tips and Tricks page.

Macros for the utmost efficiency[edit]

The full power of LaTeX resides in macros. They make your documents very dynamic and flexible. See the dedicated part.

Working in a team[edit]

See chapter Collaborative Writing of LaTeX Documents.

Document Structure[edit]

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 hierarchical constructs, including chapters, sections, subsections and paragraphs.

Global structure[edit]

When LaTeX processes an input file, it expects it to follow a certain structure. Thus every input file must contain the commands



The area between \documentclass{...} and \begin{document} is called the preamble. It normally contains commands that affect the entire document.

After the preamble, the text of your document is enclosed between two commands which identify the beginning and end of the actual 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:



Document classes[edit]

When processing an input file, LaTeX needs to know the type of document the author wants to create. This is specified with the \documentclass command. It is recommended to put this declaration at the very beginning.


Here, class specifies the type of document to be created. The LaTeX distribution provides additional classes for other documents, including letters and slides. 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. 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


which instructs LaTeX to typeset the document as an article with a base font size of 11 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:

Document Classes
article For articles in scientific journals, presentations, short reports, program documentation, invitations, ...
IEEEtran For articles with the IEEE Transactions format.
proc A class for proceedings based on the article class.
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 [8]
letter For writing letters.
beamer For writing presentations (see LaTeX/Presentations).

The standard document classes that are a part of LaTeX are built to be fairly generic, which is why they have a lot of options in common. Other classes may have different options (or none at all). Normally, third party classes come with some documentation to let you know. The most common options for the standard document classes are listed in the following table:

Document Class Options
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 formulas 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.
twocolumn Instructs LaTeX to typeset the document in two columns instead of one.
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. It also suppresses the inclusion of images and shows only a frame where they would normally occur.

For example, if you want a report to be in 12pt type on A4, but printed one-sided in draft mode, you would use:



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. Some packages come with the LaTeX base distribution. Others are provided separately. Modern TeX distributions come with a large number of packages pre-installed. The command to use a package is pretty simple: \usepackage:


command, where package is the name of the package and options is a list of keywords that trigger special features in the package. For example, to use the color package, which lets you typeset in colors, you would type:



You can pass several options to a package, each separated by a comma.


The document environment[edit]

Top matter[edit]

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:


\title{How to Structure a LaTeX Document}
\author{Andrew Roberts}
\date{December 2004}

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 title will never be typeset.

Using this approach, you can only create a title with a fixed layout. If you want to create your title freely, see the Title Creation section.


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 classes article and report, but not book.



Your abstract goes here...

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 before you begin the abstract environment:

\renewcommand{\abstractname}{Executive Summary}

Sectioning commands[edit]

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 are some of the structure commands found in simple.tex.

This chapter's content...

This section's content...

\subsection{Top Matter}
This subsection's content...

\subsubsection{Article Information}
This subsubsection's content...

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 use \begin and \end commands to indicate which content belongs to a given block.

LaTeX provides 7 levels of depth for defining sections (see table below). Each section in this table is a subsection of the one above it.

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[edit]

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 3. 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 you wish. For example, if you want to change it to "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:


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:


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 package unnumberedtotoc [1]. It provides the command


which will take care of a proper header as well. \addpart and addchap are also available. KOMA classes provide those commands by default.

If you don't want to use package unnumberedtotoc, you have to do everything by hand using \addcontentsline and \markright{} (or even \markboth{}{}).


Note that if you use PDF bookmarks you will need to add a phantom section so that hyperlinks will lead to the correct place in the document. The \phantomsection command is defined in the hyperref package, and is Commonly used like this:


For chapters you will also need to clear the page (this will also correct page numbering in the ToC):

\clearpage %or \cleardoublepage
\addcontentsline{toc}{chapter}{List of Figures}

Section number style[edit]

See Counters.

Ordinary paragraphs[edit]

Paragraphs of text come after section headings. Simply type the text and leave a blank line between paragraphs. The blank line means "start a new paragraph here": it does not mean you get a blank line in the typeset output. For formatting paragraph indents and spacing between paragraphs, refer to the Paragraph Formatting section.

Table of contents[edit]

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:


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. If the hyperref package is used and the link does not point to the correct chapter, the command \phantomsection in combination with \clearpage or \cleardoublepage can be used (see also Labels and Cross-referencing):

\addcontentsline{toc}{chapter}{List of Figures}

To change the title of the TOC, you have to paste this command \renewcommand{\contentsname}{<New table of contents title>} in your document preamble. The List of Figures (LoF) and List of Tables (LoT) names can be changed by replacing the \contentsname with \listfigurename for LoF and \listtablename for LoT.


The default ToC will list headings of level 3 and above. To change how deep the table of contents displays automatically the following command can be used in the preamble:


This will make the table of contents include everything down to paragraphs. The levels are defined above on this page. Note that this solution does not permit changing the depth dynamically.

You can change the depth of specific section type, which could be useful for PDF bookmarks (if you are using the hyperref package) :

\renewcommand*{\toclevel@chapter}{-1} % Put chapter depth at the same level as \part.
\renewcommand*{\toclevel@chapter}{0} % Put chapter depth back to its default value.

In order to further tune the display or the numbering of the table of contents, for instance if the appendix should be less detailed, you can make use of the tocvsec2 package (CTAN, doc).

Book structure[edit]

The standard LaTeX book class follows the same layout described above with some additions. By default a book will be two-sided, i.e. left and right margins will change according to the page number parity. Furthermore current chapter and section will be printed in the header.

If you do not make use of chapters, it is barely useful to use the book class.

Additionally the class provides macros to change the formatting of some places of the document. We will give you some advice on how to use them properly.[2]



% Introductory chapters
% ...

\chapter{First chapter}
% ...

\chapter{First Appendix}

\chapter{Last note}
  • The frontmatter chapters will not be numbered. Page numbers will be printed in roman numerals. Frontmatter is not supposed to have sections, so they will be numbered 0.n because there is no chapter numbering. Check the Counters chapter for a fix.
  • The mainmatter chapters works as usual. The command resets the page numbering. Page numbers will be printed in arabic numerals.
  • The \appendix macro can be used to indicate that following sections or chapters are to be numbered as appendices. Appendices can be used for the article class too:
\section{First Appendix}

Only use the \appendix macro once for all appendices.

  • The backmatter behaves like the frontmatter. It has the same issue with section numbering.

As a general rule you should avoid mixing the command order. Nonetheless all commands are optional, so you might consider using only a few.

Note that the special content like the table of contents is considered as an unnumbered chapter.

Page order[edit]

This is one traditional page order for books.

  1. Half-title
  2. Empty
  3. Title page
  4. Information (copyright notice, ISBN, etc.)
  5. Dedication if any, else empty
  6. Table of contents
  7. List of figures (can be in the backmatter too)
  8. Preface chapter
  1. Main topic
  1. Some subordinate chapters
  1. Bibliography
  2. Glossary / Index

Special pages[edit]

Comprehensive papers often feature special pages at the end, like indices, glossaries and bibliographies. Since this is a quite complex topic, we will give you details in the dedicated part Special Pages.


Any good research paper will have a complete list of references. LaTeX has two ways of inserting your references into a document:

  • 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.

To learn how to add a bibliography to your document, see the Bibliography Management section.

Notes and references[edit]

Text Formatting[edit]

This section will guide you through the formatting techniques of the text. Formatting tends to refer to most things to do with appearance, so it makes the list of possible topics quite eclectic: text style, spacing, etc. If formatting may also refer to paragraphs and to the page layout, we will focus on the customization of words and sentences for now.

A lot of 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. 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.

LaTeX is so flexible that we will actually only skim 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!


Line Spacing[edit]

If you want to use larger inter-line spacing in a document, you can change its value by putting the


command into the preamble of your document. Use \linespread{1.3} for "one and a half" line spacing, and \linespread{1.6} for "double" line spacing. Normally the lines are not spread, so the default line spread factor is 1. This may not be ideal in all situations: see .

The setspace package allows more fine-grained control over line spacing. To set "one and a half" line spacing document-wide, but not where it is usually unnecessary (e.g. footnotes, captions):


To change line spacing within the document, the setspace package provides the environments singlespace, onehalfspace, doublespace and spacing:

This paragraph has \\ default \\ line spacing.
  This paragraph has \\ double \\ line spacing.
  This paragraph has \\ huge gaps \\ between lines.

Non-breaking spaces[edit]

This essential feature is a bit unknown to newcomers, although it is available on most WYSIWYG document processors. A non-breaking space between two tokens (e.g. words, punctuation marks) prevents the processors from inserting a line break between them. Besides a non-breaking space cannot be enlarged. It is very important for a consistent reading.

LaTeX uses the '~' symbol as a non-breaking space. You would usually use non-breaking spaces for punctuation marks in some languages, for units and currencies, for initials, etc. In French typography, you would put a non-breaking space before all two-parts punctuation marks.



Space between words and sentences[edit]

To get a straight right margin in the output, LaTeX inserts varying amounts of space between the words. By default, it also inserts slightly more space at the end of a sentence. However, the extra space added at the end of sentences is generally considered typographically old-fashioned in English language printing. (The practice is found in nineteenth century design and in twentieth century typewriter styles.) Most modern typesetters treat the end of sentence space the same as the interword space. (See for example, Bringhurst's Elements of Typographic Style.) The additional space after periods can be disabled with the command


which tells LaTeX not to insert more space after a period than after ordinary character. Frenchspacing can be turned off later in your document via the \nonfrenchspacing command.

If an author wishes to use the wider end-of-sentence spacing, care must be exercised so that punctuation marks are not misinterpreted as ends of sentences. TeX assumes that sentences end with periods, question marks or exclamation marks. Although 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 non-breaking space. The command \@ in front of a period specifies that this period terminates a sentence even when it follows an uppercase letter. (If you are using \frenchspacing, then none of these exceptions need be specified.)

Stretched spaces[edit]

You can insert a horizontal stretched space with \hfill in a line so that the rest gets "pushed" toward the right margin. For instance this may be useful in the header.

Author Name \hfill \today

Similarly you can insert vertical stretched space with \vfill. It may be useful for special pages.


\section{My first section}
% ...

See Lengths for more details.

Manual spacing[edit]

The spaces between words and sentences, between paragraphs, sections, subsections, etc. is determined automatically by LaTeX. It is against LaTeX philosophy to insert spaces manually and will usually lead to bad formatting. Manual spacing is a matter of macro writing and package creation.

See Lengths for more details.


LaTeX hyphenates words whenever necessary. Hyphenation rules will vary for different languages. LaTeX only supports English by default, so if you want to have correct hyphenation rules for your desired language, see Internationalization.

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. It is known that the hyphenation algorithm does not find all correct American English hyphenation points for several words. A log of known exceptions is published periodically in the TUGboat journal. (2012 list:

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 where 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.

I think this is: su\-per\-cal\-%

LaTeX does not hyphenate compound words that contain a dash[1]. There are two packages that can add back flexibility. The hyphenat package supplies the \hyp command. This command typesets the dash and then subjects the constituent words to automatic hyphenation. After loading the package:


one should write, instead of electromagnetic-endioscopy:


The extdash package also offers features for controlling the hyphenation of compound words containing dashes — as opposed to the words themselves which it leaves to LaTeX. The shortcuts option enables a more compressed syntax:


Typical usage is as follows, assuming the compressed syntax. In both cases, LaTeX can break and hyphenate the constituent words, but in the latter case, it will not break after the L:


One or more words can be kept together on the one line with the standard LaTeX command:


This prevents hyphenation and causes its argument to be kept together under all circumstances. For 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:


You can change the degree to which LaTeX will hyphenate by changing the value of \tolerance=1000 and \hyphenpenalty=1000. You'll have to experiment with the values to achieve the desired effect. A document which has a low tolerance value will cause LaTeX not to tolerate uneven spacing between words, hyphenating words more frequently than in documents with higher tolerances. Also note that using a higher text width will decrease the probability of encountering badly hyphenated word. For example adding


will widen the text width and reduce the amount of margin overruns.


LaTeX treats left and right quotes as different entities. For single quotes, a grave accent, ` (on American keyboards, this symbol is found on the tilde key; adjacent to the number 1 key on most keyboards) gives a left quote mark, and an apostrophe, ' gives a right. For double quotes, simply double the symbols, and LaTeX will interpret them accordingly. (Don't use the " for right double quotes: when the babel package is used for some languages (e.g. German), the " is redefined to produce an umlaut accent; using " for right double quotes will either lead to bad spacing or it being used to produce an umlaut). On British keyboards, ' ` ' is left of the ' 1 ' key and shares the key with ' ¬ ', and sometimes ' ¦ ' or ' | '. The apostrophe (') key is to the right of the colon/semicolon key and shares it with the ' @ ' symbol.

To `quote' in LaTeX


To ``quote'' in LaTeX


To ``quote" in LaTeX


To ,,quote'' in LaTeX


,,German quotation marks``

Example of German quotation marks.png

<<French quotation marks>>

Example of French quotation marks.png

``Please press the `x' key.''

Latex quote 3.png

,,Proszę, naciśnij klawisz <<x>>''.

Latex quote 4.png

The right quote is also used for apostrophe in LaTeX without trouble.

For left bottom quote and European quoting style you need to use T1 font encoding enabled by:


See Fonts for more details on font encoding.

The package csquotes offers a multilingual solution to quotations, with integration to citation mechanisms offered by BibTeX. This package allows one for example to switch languages and quotation styles according to babel language selections.

Diacritics and accents[edit]

Most accents and diacritics may be inserted with direct keyboard input by configuring the preamble properly. For symbols unavailable on your keyboard, diacritics may be added to letters by placing special escaped metacharacters before the letter that requires the diacritic.

See Special Characters.

Margin misalignment and interword spacing[edit]

Some very long words, numbers or URLs may not be hyphenated properly and move far beyond the side margin. One solution for this problem is to use sloppypar environment, which tells LaTeX to adjust word spacing less strictly. As a result, some spaces between words may be a bit too large, but long words will be placed properly.

This is a paragraph with
then we have another bad thing
--- a long number 1234567890123456789.

This is a paragraph with
then we have an another bad thing
--- a long number 1234567890123456789.

LaTeX sloppypar.png

Another solution is to edit the text to avoid long words, numbers or URLs approaching the side margin.


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

Latex example ligatures.png

Ligatures can interfere with some text-search tools (a search for "finally" wouldn't find the string "nally"). The \DisableLigatures from the microtype package can disable ligatures in the whole document to increase accessibility.

\DisableLigatures{encoding = *, family = *}

Note that this will also disable ligatures such as "--" to "–", "---" to "—", etc.

If you are using XeLaTeX and OpenType fonts, the fontspec package allows for standard ligatures to be turned off as well as fancy swash ligatures to be turned on.

Another solution is to use the cmap package, which will help the reader to interpret the ligatures:


Slash marks[edit]

The normal typesetting of the / character in LaTeX does not allow following characters to be "broken" onto 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.

A word after / or \slash is not automatically hyphenated. This is a similar problem to non-hyphenation of words with a dash described under Hyphenation. One way to have both a line break and automatic hyphenation in both words is


Both / and \slash can be used with a zero \hspace like this. \slash includes a penalty to make a line break there less desirable. This combination can be made into a new slash macro if desired. The hyphenat package includes an \fshyp which will add a hyphen after the slash like "input/- output" if the line breaks there.


To change the font family, emphasize text, and other font-related issues, see Fonts.

Formatting macros[edit]

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.


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 \textit, without having to wade through your document, identifying all the occurrences of \textit and then figuring out for each one whether it was used for pointing out danger or for some other reason.

See Macros for more details.

Text mode superscript and subscript[edit]

Sub and superscripting can be done quite easily using \textsubscript{} and \textsuperscript{}.


Michelangelo was born on March 6\textsuperscript{th}, 1475.


Note: A LaTeX version from 2015 or later, or the package fixltx2e, is needed to use text-mode subscripts in all contexts.[2]

Text figures ("old style" numerals)[edit]

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:


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:


% Enclose everything in an \AtBeginDocument{}
  % Make \section{} use text figures
  \renewcommand{\thesection}{ \oldstylenums{\myTheSection} }

  % Make \paragraph{} use text figures
  \renewcommand{\theparagraph}{ \oldstylenums{\myTheParagraph} }

  % Make the page numbers in text figures
  \renewcommand{\thepage}{ \oldstylenums{\myThePage} }

Should you use additional sectioning or paragraphing commands, you may adapt the previous code listing to include them as well.


A subsequent use of the \pagenumbering command, e.g., \pagenumbering{arabic}, will reset the \thepage command back to the original. Thus, if you use the \pagenumbering command in your document, be sure to reinstate your \myThePage definition from the code above:

% without this, the \thepage command will not be in oldstyle (e.g., in your Table of Contents}
\renewcommand{\thepage}{ \oldstylenums{\myThePage} }

Dashes and hyphens[edit]

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$

Latex dashes example.png

The names for these dashes are: ‘-’(-) hyphen , ‘--’(–) en-dash , ‘---’(—) em-dash and ‘’(−) minus sign. They have different purposes:

Input Output Purpose
- - inter-word
-- page range, 1–10
--- punctuation dash—like this
$-$ minus sign

Use \hyp{} macro from hyphenat package instead of hyphen if you want LaTeX to break compound words between lines.

The commands \textendash and \textemdash are also used to produce en-dash (–), and em-dash (—), respectively.

Ellipsis (…)[edit]

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

Latex example text dots.png

Alternatively, you can use the \textellipsis command which allows the spacing between the dots to vary.

Ready-made strings[edit]

There are some very simple LaTeX commands for typesetting special text strings:

Latex ready-made strings.png


To do:
Describe microtype package -- hanging punctuation, font expansion, additional kerning.

Notes and References[edit]

This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.

Paragraph Formatting[edit]

Altering the paragraph formatting is rarely necessary in academic writing. It is primarily used for formatting text in floats or for more exotic documents.

Paragraph alignment[edit]

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.

However, if you really need to disable one of the above commands locally (for example because you have to use some broken package), you can use the command \justifying from package ragged2e.

Paragraph indent and break[edit]

By default, the first paragraph after a heading follows the standard Anglo-American publishers' practice of no indentation. The size of subsequent paragraph indents 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 it by using the \setlength command. This will set paragraph indents to 1cm:

\setlength{\parindent}{1cm} % Default is 15pt.

Whitespace in LaTeX can also be made flexible (what Lamport calls "rubber" lengths). This means that values such as extra vertical space inserted before a paragraph \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}

If you want to indent a paragraph that is not indented, you can use


at the beginning of the paragraph. Obviously, this will only have an effect when \parindent is not set to zero. If you want to indent the beginning of every section, you can use the indentfirst package: once loaded, the beginning of any chapter/section is indented by the usual paragraph indentation.

To create a non-indented paragraph, you can use


as the first command of the paragraph. This might come in handy when you start a document with body text and not with a sectioning command.

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 by changing this setting. If you want to use the style of having no indentation with a space between paragraphs, use the parskip package, which does this for you, while making adjustments to the spacing of lists and other structures which use paragraph spacing, so they don't get too far apart. If you want both indent and break, use


To indent subsequent lines of a paragraph, use the TeX command \hangindent. (While the default behaviour 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.

\paragraph line break[edit]

Default style for \paragraph may seem odd in the first place, as it writes the following text next to the title. If you do not like it, use a class other than the traditional article/book, or use ConTeXt or PlainTeX. Hacking of the class in use is really not the way LaTeX is intended to be used, and you may encounter a lot of frustrating issues.

Anyway, let's analyse the problem. If you add a manual line break with \\, LaTeX will complain that

There's no line here to end.

Simply adding an empty space will do it:

\paragraph{Title} \hspace{0pt} \\

Alternatively you can use the shorter, yet not completely equivalent syntax:

\paragraph{Title} ~\\

Line spacing[edit]

To change line spacing in the whole document use the command \linespread covered in Text Formatting.

Alternatively, you can use the \usepackage{setspace} package, which is also covered in Text Formatting. This package provides the commands \doublespacing, \onehalfspacing, \singlespacing and \setstretch{baselinestretch}, which will specify the line spacing for all sections and paragraphs until another command is used. Furthermore, the package provides the following environments in order to change line spacing within the document but not document-wide:

  • doublespace: lines are double spaced;
  • onehalfspace: line spacing set to one-and-half spacing;
  • singlespace: normal line spacing;
  • spacing: customizable line spacing, e.g. \begin{spacing}{\baselinestretch} ... \end{spacing}.

See the section on customizing lists for information on how to change the line spacing in lists.

Manual breaks[edit]

LaTeX takes care of formatting, breaks included. You should avoid manual breaking as much as possible, for it could lead to very bad formatting.

Controlling the breaks should be reserved to macro and package writers. Here follows a quick reference.

\newline Breaks the line at the point of the command.
\\ Breaks the line at the point of the command; it is usually a shorter version of the previous command, but LaTeX sometimes redefines it for several environments. This command also features the vertical space as optional parameter.
\\* Breaks the line at the point of the command and additionally prohibits a page break after the forced line break. This command also features the vertical space as optional parameter.
\\[extra-space] Command \\ has an optional argument that specifies the amount of extra vertical space to be inserted before the next line. This amount can be negative.
\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. If it cannot, it will decide whether or not to include the linebreak according to the priority you have provided.
\break (TeX) Breaks the line without filling the current line. This will result in an underful badness if you do not fill the line yourself, i.e. ...\hfill\break .... Actually \hfill\break produces the same as \newline and \\.
\par (TeX) Starts a new paragraph. It is a horizontal mode command, so you can only use it in a paragraph.

The page breaks are covered in Page Layout. More details on manual spaces between paragraphs (such as \bigskip) can be found in Lengths.

Special paragraphs[edit]

Verbatim text[edit]

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. This is ideal for typesetting program source code. Here is an example:

The verbatim environment
  simply reproduces every
 character you input,
including all  s p a c e s!


Note: once in the verbatim environment, the only command that will be recognized is \end{verbatim}. Any others will be output. The font size in the verbatim environment can be adjusted by placing a font size command before \begin{verbatim}. If this is a problem, you can use the alltt package instead, providing an environment with the same name:

Verbatim extended with the ability
to use normal commands.  Therefore, it
is possible to \emph{emphasize} words in
this environment, for example.


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. To write equations within the alltt enviroment, you can use \( and \) to enclose them, instead of the usual $.

When using \textbf{} inside the alltt enviroment, note that the standard font has no bold TT font. Txtfonts has bold fonts: just add \renewcommand{\ttdefault}{txtt} after \usepackage{alltt}.

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 except *; \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.

To use verbatim in beamer, the frame needs to be made fragile: \begin{frame}[fragile] .

Typesetting URLs[edit]

One of either the hyperref or url packages provides the \url command, which properly typesets URLs, for example:

Go to \url{} 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 (only in PDFLaTeX, not in plain LaTeX+ dvips). It was designed for Web URLs, so it understands their syntax and will never break midway 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{}. (Alternately pdfborder = {0 0 0} might work if the four zeroes do not.)

You can put the following code into your preamble to change the style, how URLs are displayed to the normal font:


See also Hyperlinks

Listing environment[edit]

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.

Multiline comments[edit]

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, unless you're using an editor that automates this process. Alternatively, you can use the verbatim package, to be loaded in the preamble as usual:


(you can also use the comment package instead) you can use an environment called comment that will comment out everything within itself. Here is an example:

This is another
rather stupid,
but helpful
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 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:


Then, to comment out text, simply do something like this:

\comment{This is a long comment and can extend over multiple lines, etc.} But it won't show.

But it won't show.

This approach can, however, produce unwanted spaces in the document, so it may work better to use


Then if you supply only one argument to \comment{}, this has the desired effect without producing extra spaces.

Another drawback is that content is still parsed and possibly expanded, so you cannot put anything you want in it (such as LaTeX commands).

Skipping parts of the source[edit]

A more robust way of making the TeX engine skip some part of the source is to use the TeX \iffalse-conditional. The typical use is

This we want to keep

\iffalse % ----- START THE CUT ---------

But this part 
we want to skip

\fi % ---------- END THE CUT -----------

Here it begins again

This we want to keep

Here it begins again

The \iffalse-conditional is always false.

Quoting text[edit]

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:

for a short quotation, or a series of small quotes, separated by blank lines.
for use with longer quotations, of more than one paragraph, because it indents the first line of each paragraph.
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 \\.


In scientific publications it is customary to start with an abstract which gives the reader a quick overview of what to expect. See Document Structure.

Notes and References[edit]

This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.


Adding colors to your text is supported by the color package. Using this package, you can set the font color, text background, or page background. You can choose from predefined colors or define your own colors using RGB, Hex, or CMYK. Mathematical formulas can also be colored.

Adding the color package[edit]

To make use of these features, the color package must be imported.


Alternatively, one can write:


The \usepackage is obvious, but the initialization of additional commands like usenames allows you to use names of the default colors, the same 16 base colors as used in HTML. The dvipsnames allows you access to more colors, another 64, and svgnames allows access to about 150 colors. The initialization of "table" allows colors to be added to tables by placing the color command just before the table. The package loaded here is the xcolor package.

If you need more colors, then you may also want to look at adding the x11names to the initialization section as well, this offers more than 300 colors, but you need to make sure your xcolor package is the most recent you can download.

Entering colored text[edit]

The simplest way to type colored text is by:


where declared-color is a color that was defined before by \definecolor.

Another possible way by

{\color{declared-color} some text}

that will switch the standard text color to the color you want. It will work until the end of the current TeX group. For example:

\emph{some black text, \color{red} followed by a red fragment}, going black again.

LaTeX colour demo 1.png

The difference between \textcolor and \color is the same as that between \texttt and \ttfamily, you can use the one you prefer. The \color environment allows the text to run over multiple lines and other text environments whereas the text in \textcolor must all be one paragraph and not contain other environments.

You can change the background color of the whole page by:


Entering colored background for the text[edit]


If the background color and the text color is changed, then:


There is also \fcolorbox to make framed background color in yet another color:


Predefined colors[edit]

The predefined color names are

black, blue, brown, cyan, darkgray, gray, green, lightgray, lime, magenta, olive, orange, pink, purple, red, teal, violet, white, yellow.

There may be other pre-defined colors on your system, but these should be available on all systems.

If you would like a color not pre-defined, you can use one of the 68 dvips colors, or define your own. These options are discussed in the following sections

The 68 standard colors known to dvips[edit]

Invoke the package with the usenames and dvipsnames option. If you are using tikz or pstricks package you must declare the xcolor package before that, otherwise it will not work.

Name Color   Name Color
Apricot     Aquamarine  
Bittersweet     Black  
Blue     BlueGreen  
BlueViolet     BrickRed  
Brown     BurntOrange  
CadetBlue     CarnationPink  
Cerulean     CornflowerBlue  
Cyan     Dandelion  
DarkOrchid     Emerald  
ForestGreen     Fuchsia  
Goldenrod     Gray  
Green     GreenYellow  
JungleGreen     Lavender  
LimeGreen     Magenta  
Mahogany     Maroon  
Melon     MidnightBlue  
Mulberry     NavyBlue  
OliveGreen     Orange  
OrangeRed     Orchid  
Peach     Periwinkle  
PineGreen     Plum  
ProcessBlue     Purple  
RawSienna     Red  
RedOrange     RedViolet  
Rhodamine     RoyalBlue  
RoyalPurple     RubineRed  
Salmon     SeaGreen  
Sepia     SkyBlue  
SpringGreen     Tan  
TealBlue     Thistle  
Turquoise     Violet  
VioletRed     White  
WildStrawberry     Yellow  
YellowGreen     YellowOrange  

Defining new colors[edit]

If the predefined colors are not adequate, you may wish to define your own.


Define the colors in the preamble of your document. (Reason: do so in the preamble, so that you can already refer to them in the preamble, which is useful, for instance, in an argument of another package that supports colors as arguments, such as the listings package.)


You need to include the xcolor package in your preamble to define new colors. In the abstract, the colors are defined following this scheme:



  • name is the name of the color; you can call it as you like
  • model is the way you describe the color, and is one of gray, rgb, RGB, HTML, and cmyk.
  • color-spec is the description of the color

Color Models[edit]

Among the models you can use to describe the color are the following (several more are described in the xcolor manual):

Color Models
Model Description Color Specification Example
gray Shades of gray
Just one number between 0 (black) and 1 (white), so 0.95 will be very light gray, 0.30 will be dark gray. \definecolor{light-gray}{gray}{0.95}
rgb Red, Green, Blue
Three numbers given in the form red,green,blue; the quantity of each color is represented with a number between 0 and 1. \definecolor{orange}{rgb}{1,0.5,0}
RGB Red, Green, Blue
Three numbers given in the form red,green,blue; the quantity of each color is represented with a number between 0 and 255. \definecolor{orange}{RGB}{255,127,0}
HTML Red, Green, Blue
Six hexadecimal numbers given in the form RRGGBB; similar to what is used in HTML. \definecolor{orange}{HTML}{FF7F00}
cmyk Cyan, Magenta, Yellow, Black
Four numbers given in the form cyan,magenta,yellow,black; the quantity of each color is represented with a number between 0 and 1. \definecolor{orange}{cmyk}{0,0.5,1,0}


To define a new color, follow the following example, which defines orange for you, by setting the red to the maximum, the green to one half (0.5), and the blue to the minimum:


The following code should give a similar results to the last code chunk.


If you loaded the xcolor package, you can define colors upon previously defined ones.

The first specifies 20 percent blue and 80 percent white; the second is a mixture of 20 percent blue and 80 percent black; and the last one is a mixture of (20*0.3) percent blue, ((100-20)*0.3) percent black and (100-30) percent green.


xcolor also feature a handy command to define colors from color mixes:


Using color specifications directly[edit]

Normally one would predeclare all the colors as above, but sometimes it is convenient to directly use a color without naming it first. To achieve this, \color and \textcolor have an alternative syntax specifying the model in square brackets, and the color specification in curly braces. For example:

{\color[rgb]{1,0,0} This text will appear red-colored}
\textcolor[rgb]{0,1,0}{This text will appear green-colored}

Creating / Capturing colors[edit]

You may want to use colors that appear on another document, web pages, pictures, etc. Alternatively, you may want to play around with rgb values to create your own custom colors.

Image processing suites like the free GIMP suite for Linux/Windows/Mac offer color picker facilities to capture any color on your screen or synthesize colors directly from their respective rgb / hsv / hexadecimal values.

Smaller, free utilities also exist:

Spot colors[edit]

Spot colors are customary in printing. They usually refer to pre-mixed inks based on a swatchbook (like Pantone, TruMatch or Toyo). The package colorspace extends xcolor to provide real spot colors. They are defined with, say:

\definespotcolor{mygreen}{PANTONE 7716 C}{.83, 0, .40, .11}



Fonts are a complex topic. For common documents, only Font families, Emphasizing text, and Font encoding are really needed. The other sections are more useful to macro writers or for very specific needs.


The digital fonts have a long and intricate history. See Adobe Font Metrics for some more details.

Originally TeX was conceived to use its own font system, MetaFont, designed by D. Knuth. The default font family for TeX and friends is called Computer Modern. These high quality fonts are scalable, and have a wide range of typographical fine tuning capabilities.

Standard tex compilers will let you use other fonts. There are many different font types, such as PostScript Type1/Type3 fonts and bitmap fonts. Type1 are outline fonts (vector graphics) which are commonly used by pdftex. Bitmap fonts are raster graphics, and usually have very poor quality, which can easily be seen when zooming or printing a document. Type3 is a superset of Type1 and has more functionalities from Postscript, such as embedding raster graphics. In the TeX world, Type3 fonts are often used to embed bitmap fonts.

It should be noticed that fonts get generated the first time they are required, hence the long compilation time.

However, MetaFont is internally a quite complex font system, and the most popular font systems as of this day are Truetype font (ttf) and OpenType font (otf). With modern TeX compilers such as xetex and luatex it is possible to make use of such fonts in LaTeX documents. If you want/have to stick with the standard compilers, the aforementioned font types must first be converted and made available to LaTeX (e.g. converted to Type1 fonts). The external links section below has some useful resources.

In LaTeX, there are many ways to specify and control fonts. It is a very complex matter in typography.

Font families[edit]

There are many font families e.g. Computer Modern, Times, Arial, and Courier. Those families can be grouped into three main categories: roman (rm) or serif, sans serif (sf) and monospace (tt) (see Typeface for more details). Each font family comes with the default design which falls into one of those categories; however, it is interchangeable among them. Computer Modern Roman is the default font family for LaTeX. Fonts in each family also have different properties (size, shape, weight, etc.). Families are meant to be consistent, so it is highly discouraged to change fonts individually rather than the whole family.

The three families are defined by their respective variables:

  • \rmdefault
  • \sfdefault
  • \ttdefault

The default family is contained in the \familydefault variable, and it is meant to have one of the three aforementioned variables as value. The default is defined (in the preamble) like the following assignment:


This will turn all the part of the document using the default font to the default sans serif, which is Computer Modern Sans Serif if you did not change the default font.

Changing font families usually works in two steps:

  1. First specify which family you want to change (rm, sf or tt).
  2. Second specify the new default family if it is not rm.

Mathematical fonts is a more complex matter. Fonts may come with a package that will take care of defining all three families plus the math fonts. You can do it by yourself, in which case you do not have to load any package.

Below is an example[1] that demonstrates how to change a specific family.

% Default font (\familydefault = \rmdefault = Computer Modern Roman)
Lorem ipsum dolor sit amet, consectitur adipiscing elit.

% Palatino font (ppl must be installed).
Lorem ipsum dolor sit amet, consectitur adipiscing elit.

% Iwona font (iwona must be installed).
Lorem ipsum dolor sit amet, consectitur adipiscing elit.

LaTeX font example.png

The three default family font variables and the \familydefault variable should not be confused with their respective switch:

  • \normalfont
  • \rmfamily
  • \sffamily
  • \ttfamily

Available LaTeX Fonts [2][edit]

To choose a font of your liking, please visit Here are some common examples.

Below are some fonts which are installed by default.

Serif Fonts[edit]

Abbreviation Font Name
cmr Computer Modern Roman (default)
lmr Latin Modern Roman
pbk Bookman
bch Charter
pnc New Century Schoolbook
ppl Palatino
ptm Times

Sans Serif Fonts[edit]

Abbreviation Font Name
cmss Computer Modern Sans Serif (default)
lmss Latin Modern Sans Serif
pag Avant Garde
phv Helvetica

Typewriter Fonts[edit]

Abbreviation Font Name
cmtt Computer Modern Typewriter (default)
lmtt Latin Modern
pcr Courier

Furthermore, the Bera Mono (BitStream Vera Mono) and LuxiMono fonts were designed to look good when used in conjunction with the Computer Modern serif font.


Cursive Fonts[edit]

Since LaTeX has no generic family group for cursive fonts, these fonts are usually assigned to the roman family.

Abbreviation Font Name
pzc Zapf Chancery

Mathematical Formula Fonts[edit]

Abbreviation Font Name
cmm Computer Modern (math italic)
cmsy Computer Modern (math symbols)
zplm Palatino (math)

Emphasizing text[edit]

In order to add some emphasis to a word or a phrase, the simplest way is to use the \emph{text} command, which usually italicizes the text. Italics may be specified explicitly with \textit{text}.

I want to \emph{emphasize} a word.


Note that the \emph command is dynamic: if you emphasize a word which is already in an emphasized sentence, it will be reverted to the upright font.

\emph{In this emphasized sentence, there is an emphasized \emph{word} which looks upright.}

In this emphasized sentence, there is an emphasized word which looks upright.

Text may be emphasized more heavily through the use of boldface, particularly for keywords the reader may be trying to find when reading the text. As bold text is generally read before any other text in a paragraph or even on a page, it should be used sparingly. It may also be used in place of italics when using sans-serif typefaces to provide a greater contrast with unemphasized text. Bold text can be generated with the \textbf{text} command.

\textbf{Bold text} may be used to heavily emphasize very important words or phrases.

Bold text may be used to heavily emphasize very important words or phrases.

Font encoding[edit]

A character is a sequence of bytes, and should not be confused with its representation, the glyph, which is what the reader sees. So the character 'a' has different representations following the used font, for example the upright version, the italic version, various weights and heights, and so on.

Upon compilation, tex will have to choose the right font glyph for every character. This is what is called font encoding. The default LaTeX font encoding is OT1, the encoding of the original Computer Modern TeX text fonts. It contains only 128 characters, many from ASCII, but leaving out some others and including a number that are not in ASCII. When accented characters are required, TeX creates them by combining a normal character with an accent. While the resulting output looks perfect, this approach has some caveats.

  • It stops the automatic hyphenation from working inside words containing accented characters.
  • Searches for words with accents in PDFs will fail.
  • Extracting ('e.g.' copy paste) the umlaut 'Ä' via a PDF viewer actually extracts the two characters '"A'.
  • Besides, some of Latin letters could not be created by combining a normal character with an accent, to say nothing about letters of non-Latin alphabets, such as Greek or Cyrillic.

To overcome these shortcomings, several 8-bit CM-like font sets were created. Extended Cork (EC) fonts in T1 encoding contains letters and punctuation characters for most of the European languages based on Latin script. The LH font set contains letters necessary to typeset documents in languages using Cyrillic script. Because of the large number of Cyrillic glyphs, they are arranged into four font encodings—T2A, T2B, T2C, and X2. The CB bundle contains fonts in LGR encoding for the composition of Greek text. By using these fonts you can improve/enable hyphenation in non-English documents. Another advantage of using new CM-like fonts is that they provide fonts of CM families in all weights, shapes, and optically scaled font sizes.

All this is not possible with OT1; that's why you may want to change the font encoding of your document.

Note that changing the font encoding will have some requirements over the fonts being used. The default Computer Modern font does not support T1. You will need Computer Modern Super (cm-super) or Latin Modern (lmodern), which are Computer Modern-like fonts with T1 support. If you have none of these, it is quite frequent (depends on your TeX installation) that tex chooses a Type3 font such as the Type3 EC, which is a bitmap font. Bitmap fonts look rather ugly when zoomed or printed.

The fontenc package tells LaTeX what font encoding to use. Font encoding is set with:


where encoding is the font encoding. It is possible to load several encodings simultaneously.

There is nothing to change in your document to use CM Super fonts (assuming they are installed), they will get loaded automatically if you use T1 encoding. For lmodern, you will need to load the package after the T1 encoding has been set:


The package ae (almost European) is obsolete. It provided some workarounds for hyphenation of words with special characters. These are not necessary any more with fonts like lmodern. Using the ae package leads to text encoding problems in PDF files generated via pdflatex (e.g. text extraction and searching), besides typographic issues.

Font styles[edit]

Each family has its own font characteristics (such as italic and bold), also known as font styles, or font properties.

Font styles are usually implemented with different font files. So it is possible to build a new font family by specifying the font styles of different font families.


The following table lists the commands you will need to access the typical font shapes:

LaTeX command Equivalent to Output style Remarks
\textnormal{...} {\normalfont ...} document font family This is the default or normal font.
\emph{...} {\em ...} emphasis Typically italics. Using emph{} inside of italic text removes the italics on the emphasized text.
\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 to, but slightly different from, italics).
\textsc{...} {\scshape ...} Small Capitals
\uppercase{...} uppercase (all caps) Also \lowercase. There are some caveats, though; see here.
\textbf{...} {\bfseries ...} bold
\textmd{...} {\mdseries ...} medium weight A font weight in between normal and bold.
\textlf{...} {\lfseries ...} light A font weight lighter than normal. Not supported by all typefaces.

The commands in column two are not entirely equivalent to the commands in column one: They do not correct spacing after the selected font style has ended. The commands in column one are therefore in general recommended.

You may have noticed the absence of underline. This is because underlining is not recommended for typographic reasons (it weighs the text down). You should use emph instead. However underlining text provides a useful extra form of emphasis during the editing process, for example to draw attention to changes. Although underlining is available via the \underline{...} command, text underlined in this way will not break properly. This functionality has to be added with the ulem (underline emphasis) 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 restore the usual \emph formatting, add \normalem straight after the document environment begins. Alternatively, use \usepackage[normalem]{ulem}.
  • To underline, use \uline{...} along with \usepackage[normalem]{ulem}..
  • To add a wavy underline, use \uwave{...} along with \usepackage[normalem]{ulem}..
  • For a strike-out (strikethrough), use \sout{...} along with \usepackage[normalem]{ulem}..
  • For a slash through each individual character \xout{...} along with \usepackage[normalem]{ulem}.

Some font styles are not compatible one with the other. But some extra packages will fill this hole. For bold small capitals, you might want to use:

% ...
\textsc{ \textbf{This is bold small capitals} }

Sizing text[edit]

To apply different font sizes, simply follow the commands on this table:

Command Output
\tiny sample text
\scriptsize sample text
\footnotesize sample text
\small sample text
\normalsize sample text
\large sample text
\Large sample text
\LARGE sample text
\huge sample text
\Huge sample text

These commands change the size within a given scope, so for instance {\Large some words} will change the size of only some words, and does not affect the font in the rest of the document. It will work for most parts of the text.


These commands cannot be used in math mode. However, part of a formula may be set in a different size by using an \mbox command containing the size command. The new size takes effect immediately after the size command; if an entire paragraph or unit is set in a certain size, the size command should include the blank line or the \end{...} which delimits the unit.

The default for \normalsize is 10 point (option 10pt), but it may differ for some Document Styles or their options. The actual size produced by these commands also depends on the Document Style and, in some styles, more than one of these size commands may produce the same actual size.

Note that the font size definitions are set by the document class. Depending on the document style the actual font size may differ from that listed above. And not every document class has unique sizes for all 10 size commands.

Absolute Point Sizes
size standard classes (except slides), beamer AMS classes, memoir slides
[10pt] [11pt] [12pt] [10pt] [11pt] [12pt]
\tiny 5 6 6 6 7 8 13.82
\scriptsize 7 8 8 7 8 9 16.59
\footnotesize 8 9 10 8 9 10 16.59
\small 9 10 10.95 9 10 10.95 16.59
\normalsize 10 10.95 12 10 10.95 12 19.907
\large 12 12 14.4 10.95 12 14.4 23.89
\Large 14.4 14.4 17.28 12 14.4 17.28 28.66
\LARGE 17.28 17.28 20.74 14.4 17.28 20.74 34.4
\huge 20.74 20.74 24.88 17.28 20.74 24.88 41.28
\Huge 24.88 24.88 24.88 20.74 24.88 24.88 41.28

As a technical note, points in TeX follow the standard American point size in which 1 pt is approximately 0.35136 mm. The standard point size used in most modern computer programs (known as the desktop publishing point or PostScript point) has 1 pt equal to approximately 0.3527 mm while the standard European point size (known as the Didot point) had 1 pt equal to approximately 0.37597151 mm (see: point (typography)).

Local font selection[edit]

You can change font for a specific part of the text. There are four font properties you can change.

The font encoding, such as OT1 (TeX default) or T1 (extended characters support, better PDF support, widely used).
The font family.
The series: l=light, m=medium, b=bold, bx=very bold.
The shape: it=italic, n=normal, sl=slanted, sc=small capitals.
Some text in anttlc...

The \selectfont command is mandatory, otherwise the font will not be changed. It is highly recommended to enclose the command in a group to cleanly return to the previous font selection when desired.

You can use all these commands in a row:

Some text in anttlc...

The default values are stored in \encodingdefault, \familydefault, \seriesdefault and \shapedefault. Setting back the default font properties can be done with


For short, you can use the \usefont{<encoding>}{<family>}{<series>}{<shape>} command.

\usefont{T1}{cmr}{m}{n} % Computer Modern Roman (TeX default) in T1 encoding. May lead to bad text quality if you do not have cm-super installed.
\usefont{T1}{phv}{m}{sc} % phv family (sans serif) medium small capitals.
\usefont{T1}{ptm}{b}{it} % ptm family bold italic
\usefont{U}{pzd}{m}{n}   % ...

Arbitrary font size[edit]

The \tiny...\Huge commands are often enough for most contents. These are fixed sizes however. In most document processors, you can usually choose any size for any font. This is because the characters actually get magnified. If it usually looks correct for medium sizes, it will look odd at extreme sizes because of an unbalanced thickness. In TeX it is possible to change the magnification of anything, but highly discouraged for the aforementioned reason. Changing the font size is made by changing the font file. Yes, there is a file for every size: cmr10 for Computer Modern Roman 10pt, cmr12 for Computer Modern Roman 12pt, etc. This ensure the characters are correctly balanced and remain readable at all defined sizes.

You may choose a particular font size with the \fontsize{<size>}{<line space>} command. Example:

{\fontsize{5cm}{5.5cm}\selectfont This is big!}

If you are using the default Computer Modern font encoding, you may get the following message:

LaTeX Font Warning: Font shape `OT1/cmr/m/n' in size <142.26378> not available
(Font)              size <24.88> substituted on input line 103.

In that case you will notice that the font size is by default restricted to a set of fixed sizes as noted above. You can use the fix-cm or type1cm packages to allow computer modern fonts to be scaled to arbitrary values.

Finding fonts[edit]

You will find a huge font directory along examples and configurations at TUG Font Catalogue.

Using arbitrary system fonts[edit]

If you use the XeTeX or LuaTeX engine and the fontspec package, you'll be able to use any font installed in the system effortlessly. XeTeX also allows using OpenType technology of modern fonts like specifying alternate glyphs and optical size variants. XeTeX also uses Unicode by default, which might be helpful for font issues.

To use the fonts, simply load the fontspec package and set the font:



Lorem ipsum...

Then compile the document with xelatex or lualatex. Note that you can only generate .pdf files, and that you need a sufficiently recent TeX distribution (TeX Live 2009 should work for XeTeX and Tex Live 2010 for LuaTeX). Also you should not load the inputenc or fontenc package. Instead make sure that your document is encoded as UTF-8 and load fontspec, which will take care of the font encoding. To make your document support both pdflatex and xelatex/lualatex you can use the \ifxetex/ \ifluatex macro from the ifxetex/ ifluatex package. For example for xelatex


  \defaultfontfeatures{Ligatures=TeX} % To support LaTeX quoting style
  \setromanfont{Hoefler Text}

Lorem ipsum...

PDF fonts and properties[edit]

PDF documents have the capability to embed font files. It makes them portable, hence the name Portable Document Format.

Many PDF viewers have a Properties feature to list embedded fonts and document metadata.

Many Unix systems make use of the poppler tool set which features pdfinfo to list PDF metadata, and pdffonts to list embedded fonts.

Useful websites[edit]

TrueType (ttf) fonts[edit]


  1. found at the Google discussion group latexlovers
  2. Taken from

List Structures[edit]

Convenient and predictable list formatting is one of the many advantages of using LaTeX. Users of WYSIWYG word processors can sometimes be frustrated by the software's attempts to determine when they intend lists to begin and end. As a mark-up language, LaTeX gives more control over the structure and content of lists.

List structures[edit]

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 types:

  • itemize for a bullet list
  • enumerate for an enumerated list and
  • description for a descriptive list.

All lists follow the basic format:

\item The first item 
\item The second item 
\item The third etc \ldots 

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.

Try out the examples below, to see what the lists look like in a real document.

\item \blindtext
\item \blindtext
\item \blindtext
\item \blindtext
\item [Ant] \blindtext
\item [Elephant] \blindtext
Sample output of lists in LaTeX. Itemize, enumerate and description.

LaTeX will happily allow you to insert a list environment into an existing one (up to a depth of four, more levels are available using packages). Simply begin the appropriate environment at the desired point within the current list. Latex will sort out the layout and any numbering for you.

\item The first item
\item Nested item 1
\item Nested item 2
\item The second item
\item The third etc \ldots


Some special lists[edit]

Sometimes you feel the need to better align the different list items. If you are using a KOMA-script class (or package scrextend), the labeling environment is handy. It takes a mandatory argument that contains the longest of your labels.

\item [ant] really busy all the time
\item [chimp] likes bananas
\item [alligator] very dangerous animal, sharp teeth, long
muscular tail and a bit of text that is longer than one
line and shows the alignment of text quite nicely


If you are on tight space limitations and only have short item descriptions, you may want to have the list inline. Please note that the example also shows how to change the font.

\blindtext Coco likes fruit. Her favorites are:
\item bananas
\item apples
\item oranges and
\item lemons.


Need some details on Colors?

If you want a horizontal list, package tasks can be handy. In combination with a package like exsheets, you can prepare exam papers for students.

Which one of the entries does not fit with the others?
\task mercury
\task iron
\task lead
\task zinc


Customizing lists[edit]

Especially when dealing with lists containing of just a few words per item, the standard lists take up too much space and you want to customize the appearance. Package enumitem helps you by providing a simple interface.

You can change the appearance of lists globally in the preamble, or just for single lists using the optional argument of the environment. Have a look at the following example where the list on the right is more compact using noitemsep.

\item more work
\item more responsibility
\item more satisfaction
\item more work
\item more responsibility
\item more satisfaction


An example for alignment and the width of the label.

\blindtext Coco likes fruit. Her favourites are:
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail


The documentation of package enumitem goes into more detail with respect to what can be changed and how. You can even define your own lists. Environments like labeling and tasks can be changed differently, details can be found in the package documentation respectively.

Easylist package[edit]

The easylist package allows you to create list using a more convenient syntax and with infinite nested levels. It is also very customizable.

Load the package with the control character as optional argument:


The easylist environment will default to enumerations.

& Main item~:
&& Sub item.
&& Another sub item.

It features predefined styles which you can set as optional argument.

% ...

Available styles:

  • tractatus
  • checklist - All items have empty check boxes next to them
  • booktoc - Approximately the format used by the table of contents of the book class
  • articletoc - Approximately the format used by the table of contents of the article class
  • enumerate - The default
  • itemize

You can customize lists with the \ListProperties(...) command and revert back the customization with \NewList. Yes, that's parentheses for \ListProperties parameters.

The Style parameter sets the style of counters and text, the Style* parameter sets the style of counters, and the Style** parameter sets the style of text. The parameter Numbers determines the way that the numbers are displayed and the possible values are r or R (for lower and upper case Roman numerals), l or L (for lower and upper case letters), a (for Arabic numbers, the default), and z (for Zapf's Dingbats).

The FinalMark parameter sets the punctuation of the final counter (Ex: FinalMark3={)}) while FinalSpace sets the amount of space between the item and the item's text. The Margin parameter sets the distance from the left margin (Ex: FinalSpace2=1cm). The Progressive parameter sets the distance from the left margin of all items in proportion to their level.

The Hide = n parameter prevents the first n counters from appearing in all levels. If there is a number after a parameter (Ex: Style3*) then this numbers indicates the level that it will affect (Ex: Style3=\color{red}).

Example of custom enumerate:

& Main item~:
&& Sub item.
&& Another sub item.

Note that we put the FinalMark argument between {} to avoid LaTeX understanding it as the end of the properties list. Now we change the default properties to print a custom itemize:

\ListProperties(Hide=100, Hang=true, Progressive=3ex, Style*=-- ,
Style2*=$\bullet$ ,Style3*=$\circ$ ,Style4*=\tiny$\blacksquare$ )
% ...

& Blah
& Blah
&& Blah
&&& Blah
&&&& Blah
&&&&& Blah

– Blah
     – Blah

Spaces in Style parameters are important. The Style* parameter acts as a default value and easylist will use a medium dash for level 1, 5 and onward.

You can also define custom styles using LaTeX macros:

\newcommand\myitemize{\ListProperties(Hide=100, Hang=true, Progressive=3ex, Style*=$\star$ )}

% ...
\begin{easylist} \myitemize
& Blah

Important note: easylist has some drawbacks. First if you need to put an easylist inside an environment using the same control character as the one specified for easylist, you may get an error. To circumvent it, use the following commands provided by easylist:

& ...

Besides using easylist along with figures may cause some trouble to the layout and the indentation. LaTeX lists do not have this problem.

To use easylist with Beamer, each frame that uses easylist must be marked as fragile:


Special Characters[edit]

In this chapter we will tackle matters related to input encoding, typesetting diacritics and special characters.

In the following document, we will refer to special characters for all symbols other than A-Za-z0-9 and English punctuation marks.

This chapter is tightly linked with the font encoding issue. You should have a look at Fonts on the topic.

Some languages usually need a dedicated input system to ease document writing. This is the case for Arabic, Chinese, Japanese, Korean and others. This specific matter will be tackled in Internationalization.

The rules for producing characters with diacritical marks, such as accents, differ somewhat depending whether you are in text mode, math mode, or the tabbing environment.

Input encoding[edit]

A technical matter[edit]

Most modern computer systems allow you to input letters of alphabets with non-ASCII characters directly from the keyboard. If you try to input these special characters in your LaTeX source file and compiled it, you may notice that they do not get printed at all.

A LaTeX source document is a plain text file. A computer stores data in a binary format, that is a sequence of bits (0 and 1). To display a plain text file, we need a code which tells which sequence of bits corresponds to which sequence of characters. This association is called input encoding, character encoding, or more informally charset.

For historical reasons, there are many different input encodings. There is an attempt to unify all the encoding with a specification that contains all existent symbols that are known from human history. This specification is Unicode. It only defines code points, which is a number for a symbol, but not the way symbols are represented in binary value. For that, unicode encodings are in charge. There are also several unicode encodings available, UTF-8 being one of them.

The ASCII encoding is an encoding which defines 128 characters on 7 bits. Its widespread use has led the vast majority of encodings to have backward compatibility with ASCII, by defining the first 128 characters the same way. The other characters are added using more bits (8 or more).

This is actually a big issue, since if you do not use the right encoding to display a file, it will show weird characters. What most programs try to do is guess statistically the encoding by analyzing the frequent sequences of bits. Sadly, it is not 100% safe. Some text editors may not bother guessing the encoding and will just use the OS default encoding. You should consider that other people might not be able to display directly your input files on their computer, because the default encoding for text file is different. It does not mean that the user cannot use another encoding, besides the default one, only that it has to be configured. For example, the German umlaut ä on OS/2 is encoded as 132, with Latin1 it is encoded as 228, while in Cyrillic encoding cp1251 this letter does not exist at all. Therefore you should consider encoding with care.

The following table shows the default encodings for some operating systems.

Operating system Default Encodings
Western Latin Cyrillic
Modern Unices (*BSD, Mac OS X, GNU/Linux) utf-8 utf-8
Mac (before OS X) applemac maccyr
Unix (Old) latin1 koi8-ru
Windows ansinew, cp1252 cp1251
DOS, OS/2 cp850 cp866nav

UTF-8 and Latin1 are not compatible. It means that if you try to open a Latin1-encoded file using a UTF-8 decoding, it will display odd symbols only if you used accents in it, since both encoding are ASCII superset they encode the classic letters the same way. There aren't many advantages in using Latin1 over UTF-8, which is technically superior. UTF-8 is also becoming the most widely used encoding (on the Web, in modern Unices, etc.).

Dealing with LaTeX[edit]

TeX uses ASCII by default. But 128 characters is not enough to support non-english languages. TeX has its own way to do that with commands for every diacritical marking (see Escaped codes). But if we want accents and other special characters to appear directly in the source file, we have to tell TeX that we want to use a different encoding.

There are several encodings available to LaTeX:

  • ASCII: the default. Only bare english characters are supported in the source file.
  • ISO-8859-1 (a.k.a. Latin 1): 8-bits encoding. It supports most characters for latin languages, but that's it.
  • UTF-8: a Unicode multi-byte encoding. Supports the complete Unicode specification.
  • Others...

In the following we will assume you want to use UTF-8.

There are some important steps to specify encoding.

  • Make sure your text editor decodes the file in UTF-8.
  • Make sure it saves your file in UTF-8. Most text editors do not make the distinction, but some do, such as Notepad++.
  • If you are working in a terminal, make sure it is set to support UTF-8 input and output. Some old Unix terminals may not support UTF-8. PuTTY is not set to use UTF-8 by default, you have to configure it.
  • Tell LaTeX that the source file is UTF-8 encoded.

inputenc [2] package tells LaTeX what the text encoding format of your .tex files is.

The inputenc package allows as well the user to change the encoding within the document by means of the command \inputencoding{'encoding name'}.

% ...
% In this area
% The UTF-8 encoding is specified.
% ...
% ...
% Here the text encoding is specified as ISO Latin-1.
% ...
% Back to the UTF-8 encoding.
% ...

Extending the support[edit]

The LaTeX support of UTF-8 is fairly specific: it includes only a limited range of unicode input characters. It only defines those symbols that are known to be available with the current font encoding. You might encounter a situation where using UTF-8 might result in error:

! Package inputenc Error: Unicode char \u8:ũ not set up for use with LaTeX.

This is due to the utf8 definition not necessarily having a mapping of all the character glyphs you are able to enter on your keyboard. Such characters are for example

ŷ Ŷ ũ Ũ ẽ Ẽ ĩ Ĩ

In such case, you may try need to use the utf8x option to define more character combinations. utf8x is not officially supported, but can be viable in some cases. However it might break up compatibility with some packages like csquotes.

Another possiblity is to stick with utf8 and to define the characters yourself. This is easy:

\DeclareUnicodeCharacter{'codepoint'}{'TeX sequence'}

where codepoint is the unicode codepoint of the desired character. TeX sequence is what to print when the character matching the codepoint is met. You may find codepoints on this site. Codepoints are easy to find on the web. Example:


Now inputting 'ŷ' will effectively print 'ŷ'.

With XeTeX and LuaTeX the inputenc package is no longer needed. Both engines support UTF-8 directly and allow the use of TTF and OpenType fonts to support Unicode characters. See the Fonts section for more information.

Escaped codes[edit]

In addition to direct UTF-8 input, LaTeX supports the composition of special characters. This is convenient if your keyboard lacks some desired accents and other diacritics.

The following accents may be placed on letters. Although 'o' letter is used in most of the examples, the accents may be placed on any letter. Accents may even be placed above a "missing" letter; for example, \~{} produces a tilde over a blank space.

The following commands may be used only in paragraph (default) or LR (left-right) mode.

LaTeX command Sample Description
\`{o} ò grave accent
\'{o} ó acute accent
\^{o} ô circumflex
\"{o} ö umlaut, trema or dieresis
\H{o} ő long Hungarian umlaut (double acute)
\~{o} õ tilde
\c{c} ç cedilla
\k{a} ą ogonek
\l{} ł barred l (l with stroke)
\={o} ō macron accent (a bar over the letter)
\b{o} o bar under the letter
\.{o} ȯ dot over the letter
\d{u} dot under the letter
\r{a} å ring over the letter (for å there is also the special command \aa)
\u{o} ŏ breve over the letter
\v{s} š caron/háček ("v") over the letter
\t{oo} o͡o "tie" (inverted u) over the two letters
\o ø slashed o (o with stroke)

To place a diacritic on top of an i or a j, its dot has to be removed. The dotless version of these letters is accomplished by typing \i and \j. For example:

  • \^{\i} should be used for i circumflex 'î';
  • \"{\i} should be used for i umlaut 'ï'.

If a document is to be written completely in a language that requires particular diacritics several times, then using the right configuration allows those characters to be written directly in the document. For example, to achieve easier coding of umlauts, the babel package can be configured as \usepackage[german]{babel}. This provides the short hand "o for \"o. This is very useful if one needs to use some text accents in a label, since no backslash will be accepted otherwise.

More information regarding language configuration can be found in the Internationalization section.

Less than < and greater than >[edit]

The two symbols '<' and '>' are actually ASCII characters, but you may have noticed that they will print '¡' and '¿' respectively. This is a font encoding issue. If you want them to print their real symbol, you will have to use another font encoding such as T1, loaded with the fontenc package. See Fonts for more details on font encoding.

Alternatively, they can be printed with dedicated commands:


Euro currency symbol[edit]

When writing about money these days, you need the euro sign. The textcomp package features a \texteuro command which gives you the euro symbol as supplied by your current text font. Depending on your chosen font this may be quite far from the official symbol.

An official version of the euro symbol is provided by eurosym. Load it in the preamble (optionally with the official option):


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.) you can use a different option:


again you can insert the euro symbol with \euro{}.

Alternatively you can use the marvosym package which also provides the official euro symbol.

% ...


Now that you have succeeded in printing a euro sign, you may want the '€' on your keyboard to actually print the euro sign as above. There is a simple method to do that. You must make sure you are using UTF-8 encoding along with a working \euro{} or \EUR{}command.

% or

Complete example:


Degree symbol for temperature and math[edit]

The easiest way to print temperature and angle values is to use the \SI{value}{unit} command from the siunitx package, which works both in text and math mode:


A \SI{45}{\degree} angle.

It is $\SI{17}{\degreeCelsius}$ outside.

For more information, see the documentation of the siunitx package.

A common mistake is to use the \circ command. It will not print the correct character (though $^\circ$ will). Use the textcomp package instead, which provides a \textdegree command.


A $45$\textdegree angle.

For temperature, you can use the same command or opt for the gensymb package and write


17\,\celsius % best (with textcomp)

Some keyboard layouts feature the degree symbol, you can use it directly if you are using UTF-8 and textcomp. For better results (font quality) we recommend the use of an appropriate font, like lmodern:


% ...


17\,% best

Other symbols[edit]

LaTeX has many 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:

Command Sample Character
\%  %
\$ $
\{ {
\_ _
\ddag n/a
\textbar n/a |
\textgreater >
\textendash n/a
\texttrademark n/a
\textexclamdown n/a ¡
\textsuperscript{a} a
\pounds n/a £
\# #
\& &
\} }
\S §
\dag n/a
\textbackslash n/a \
\textless <
\textemdash n/a
\textregistered n/a ®
\textquestiondown n/a ¿
\textcircled{a} n/a
\copyright n/a ©

Not mentioned in above table, tilde (~) is used in LaTeX code to produce non-breakable space. To get printed tilde sign, either write \~{} or \textasciitilde{}. And a visible space can be created with \textvisiblespace.

For some more interesting symbols, the Postscript ZipfDingbats font is available thanks to the pifont package. Add the declaration to your preamble: \usepackage{pifont}. Next, the command \ding{number}, will print the specified symbol. Here is a table of the available symbols:

ZapfDingbats symbols.

In special environments[edit]

Math mode[edit]

Several of the above and some similar accents can also be produced in math mode. The following commands may be used only in math mode.

LaTeX command Sample Description Text-mode equivalence
\hat{o} circumflex \^
\widehat{oo} wide version of \hat over several letters
\check{o} vee or check \v
\tilde{o} tilde \~
\widetilde{oo} wide version of \tilde over several letters
\acute{o} acute accent \'
\grave{o} grave accent \`
\dot{o} dot over the letter \.
\ddot{o} two dots over the letter (umlaut in text-mode) \"
\breve{o} breve \u
\bar{o} macron \=
\vec{o} vector (arrow) over the letter

When applying accents to letters i and j, you can use \imath and \jmath to keep the dots from interfering with the accents:

LaTeX command Sample Description Sample with upper dot
\hat{\imath} circumflex on letter i without upper dot
\vec{\jmath} vector (arrow) on letter j without upper dot

Tabbing environment[edit]

Some of the accent marks used in running text have other uses in the tabbing environment. In that case they can be created with the following command:

  • \a' for an acute accent
  • \a` for a grave accent
  • \a= for a macron accent

Unicode keyboard input[edit]

Some operating systems provide a keyboard combination to input any Unicode code point, the so-called unicode compose key.

Many X applications (*BSD and GNU/Linux) support the Ctrl+Shift+u combination. A 'u' symbol should appear. Type the code point and press enter or space to actually print the character. Example:

<Ctrl+Shift+u> 20AC <space>

will print the euro character.

Desktop environments like GNOME and KDE may feature a customizable compose key for more memorizable sequences.

Xorg features advanced keyboard layouts with variants that let you enter a lot of characters easily with combination using the aprioriate modifier, like Alt Gr. It highly depends on the selected layout+variant, so we suggest you to play a bit with your keyboard, preceeding every key and dead key with the Alt Gr modifier.

External links[edit]

Notes and References[edit]

  1. For a quick explanation on character sets, see this article on Joel Spolski's blog.
  2. For a detailed information on the package, see complete specifications written by the package's authors.


LaTeX has to be configured and used appropriately when it is used to write documents in languages other than English. This has to address three main areas:

  1. LaTeX needs to know how to hyphenate the language(s) to be used.
  2. The user needs to use language-specific typographic rules. In French for example, there is a mandatory space before each colon character (:).
  3. The input of special characters, especially for languages using an input system (Arab, Chinese, Japanese, Korean).

It is convenient to be able to insert language-specific special characters directly from the keyboard instead of using cumbersome coding (for example, by typing ä instead of \"{a}). This can be done by configuring input encoding properly. We will not tackle this issue here: see the Special Characters chapter.

Some languages require special fonts with the proper font encoding set. See Font encoding.

Some of the methods described in this chapter may be useful when dealing with non-English author names in bibliographies.

Here is a collection of suggestions about writing a LaTeX document in a language other than English. If you have experience in a language not listed below, please add some notes about it.


Most non-english language will need to input special characters very often. For a convenient writing you will need to set the input encoding and the font encoding properly.

The following configuration is optimal for many languages (most latin languages). Make sure your document is saved using the UTF-8 encoding.


For more details check Font encoding and Special Characters.


The babel package by Johannes Braams and Javier Bezos will take care of everything (with XeTeX and LuaTeX you should consider polyglossia). You can load it in your preamble, providing as an argument name of the language you want to use (usually its English name, but not always):


You should place it soon after the \documentclass command, so that all the other packages you load afterwards will know the language you are using. Babel will automatically activate the appropriate hyphenation rules for the language you choose. If your LaTeX format does not support hyphenation in the language of your choice, babel will still work but will disable hyphenation, which has quite a negative effect on the appearance of the typeset document. Babel also specifies new commands for some languages, which simplify the input of special characters. See the sections about languages below for more information.

If you call babel with multiple languages:


then the last language in the option list will be active (i.e. languageB), and you can use the command


to change the active language. You can also add short pieces of text in another language using the command

\foreignlanguage{languageB}{Text in another language}

Babel also offers various environments for entering larger pieces of text in another language:

Text in language B. This environment switches all language-related definitions, like the language 
specific names for figures, tables etc. to the other language.

The starred version of this environment typesets the main text according to the rules of the other language, but keeps the language specific string for ancillary things like figures, in the main language of the document. The environment hyphenrules switches only the hyphenation patterns used; it can also be used to disallow hyphenation by using the language name 'nohyphenation' (but note selectlanguage* is preferred).

The babel manual provides much more information on these and many other options.

Multilingual versions[edit]

It is possible in LaTeX to typeset the content of one document in several languages and to choose upon compilation which language to output. This might be convenient to keep a consistent sectioning and formatting across the different languages. It is also useful if you make use of multiple proper nouns and other untranslated content. Using the commands above in multilingual documents can be cumbersome, and therefore babel provides a way to define shorter names. With

\babeltags{de = german}

You can write:

text \textde{German text} text
German text

Alternative choice using iflang[edit]

The current language can also be tested by using the iflang package by Heiko Oberdiek (the built-in feature from the babel package is not reliable). Here comes a simple example:


This allows to easily distinguish between two languages without the need of defining own commands. The babel language is changed by setting


Specific languages[edit]

Arabic script[edit]

For languages which use the Arabic script, including Arabic, Persian, Urdu, Pashto, Kurdish, Uyghur, etc., add the following code to your preamble:


You can input text in either romanized characters or native Arabic script encodings. Use any of the following commands and environments to enter in text:

\< ... >
\RL{ ... }
\begin{arabtext} ... \end{arabtext}.

See the ArabTeX Wikipedia article for further details.

You may also use the Arabi package within Babel to typeset Arabic and Persian


You may also copy and paste from PDF files produced with Arabi thanks to the support of the cmap package. You may use Arabi with LyX, or with tex4ht to produce HTML.

See Arabi page on CTAN


The Armenian script uses its own characters, which will require you to install a text editor that supports Unicode and will allow you to enter UTF-8 text, such as Texmaker or WinEdt. These text editors should then be configured to compile using XeLaTeX.

Once the text editor is set up to compile with XeLaTeX, the fontspec package can be used to write in Armenian:

\setmainfont{DejaVu Serif}



The Sylfaen font lacks italic and bold, but DejaVu Serif supports them.

See Armenian Wikibooks for further details, especially on how to configure the Unicode supporting text editors to compile with XeLaTeX.

Cyrillic script[edit]

Version 3.7h of babel includes support for the T2* encodings and for typesetting Bulgarian, Russian and Ukrainian texts using Cyrillic letters[1]. Support for Cyrillic is based on standard LaTeX mechanisms plus the fontenc and inputenc packages. AMS-LaTeX packages should be loaded before fontenc and babel(Why?). If you are going to use Cyrillics in mathmode, you also need to load mathtext package before fontenc:



Generally, babel will automatically choose the default font encoding, for the above three languages this is T2A. However, documents are not restricted to a single font encoding. For multilingual documents using Cyrillic and Latin-based languages it makes sense to include Latin font encoding explicitly. Babel will take care of switching to the appropriate font encoding when a different language is selected within the document.

On modern operating systems it is beneficial to use Unicode (utf8 or utf8x) instead of KOI8-RU (koi8-ru) as an input encoding for Cyrillic text.

In addition to enabling hyphenations, translating automatically generated text strings, and activating some language specific typographic rules (like \frenchspacing), babel provides some commands allowing typesetting according to the standards of Bulgarian, Russian, or Ukrainian languages.

For all three languages, language specific punctuation is provided: the Cyrillic dash for the text (it is little narrower than Latin dash and surrounded by tiny spaces), a dash for direct speech, quotes, and commands to facilitate hyphenation:

Key combination Action
"| No ligature at this position.
"- Explicit hyphen sign, allowing hyphenation in the rest of the word.
"--- Cyrillic emdash in plain text.
"--~ Cyrillic emdash in compound names (surnames).
"--* Cyrillic emdash for denoting direct speech.
"" Similar to "-, but it produces no hyphen sign (used for compound words with hyphen, e.g. x-""y or some other signs as “disable/enable”).
"~ Compound word mark without a breakpoint.
"= Compound word mark with a breakpoint, allowing hyphenation in the composing words.
", Thinspace for initials with a breakpoint in a following surname.
"‘ German opening double quote (,,).
"’ German closing double quote (“).
"< French opening double quote (<<).
"> French closing double quote (>>).

The Russian and Ukrainian options of babel define the commands


which act like \Alph and \alph (commands for turning counters into letters, e.g. a, b, c...), but produce capital and small letters of Russian or Ukrainian alphabets (whichever is the active language of the document).

The Bulgarian option of babel provides the commands


which make \Alph and \alph produce letters of either Bulgarian or Latin (English) alphabets. The default behaviour of \Alph and \alph for the Bulgarian language option is to produce letters from the Bulgarian alphabet.

See the Bulgarian translation of "The Not So Short Introduction to LaTeX" [2] for a method to type Cyrillic letters directly from the keyboard using a different distribution.


One possible Chinese support is made available thanks to the CJK package collection. If you are using a package manager or a portage tree, the CJK collection is usually in a separate package because of its size (mainly due to fonts).

Make sure your document is saved using the UTF-8 character encoding. See Special Characters for more details. Put the parts where you want to write chinese characters in a CJK environment.



You can mix latin letters and chinese.


The last argument specifies the font. It must fit the desired language, since fonts are different for Chinese, Japanese and Korean. Possible choices for Chinese include:

  • gbsn (简体宋体, simplified Chinese)
  • gkai (简体楷体, simplified Chinese)
  • bsmi (繁体细上海宋体, traditional Chinese)
  • bkai (繁体标楷体, traditional Chinese)


Czech is fine using


UTF-8 allows you to have „czech quotation marks“ directly in your text. Otherwise, there are macros \clqq and \crqq to produce left and right quote. You can place quotated text inside \uv.


Finnish language hyphenation is enabled with:


This will also automatically change document language (section names, etc.) to Finnish.


You can load French language support with the following command:


There are multiple options for typesetting French documents, depending on the flavor of French: french, frenchb, and francais for Parisian French, and acadian and canadien for new-world French. If you do not know or do not really care, we would recommend using frenchb.

However, as of version 3.0 of babel-french, it is advised to choose the language as a global option with the following command[3]:


All enable French hyphenation, if you have configured your LaTeX system accordingly. All of these also change all automatic text into French: \chapter prints Chapitre, \today prints the current date in French and so on. A set of new commands also becomes available, which allows you to write French input files more easily. Check out the following table for inspiration:

input code rendered output
\og guillemets \fg{} « guillemets »
M\up{me}, D\up{r} Mme, Dr
1\ier{}, 1\iere{}, 1\ieres{} 1er, 1re, 1res
2\ieme{} 4\iemes{} 2e 4es
\No 1, \no 2 N° 1, n° 2
20~\degres C, 45\degres 20 °C, 45°
M. \bsc{Durand} M. Durand
\nombre{1234,56789} 1 234,567 89

You may want to typeset guillemets and other French characters directly if your keyboard have them. Running Xorg (*BSD and GNU/Linux), you may want to use the oss variant which features some nice shortcuts, like

Key combination Character
Alt Gr + w «
Alt Gr + x  »
Alt Gr + Shift + é É
Alt Gr + Shift + è È
Alt Gr + Shift + ç Ç

You will need the T1 font encoding for guillemets to print properly.

For the degree character you will get an error like

! Package inputenc Error: Unicode char \u8:° not set up for use with LaTeX.

The textcomp package will fix it for you.

The great advantage of Babel for French is that it will handle some elements of French typography for you, especially non-breaking spaces before all two-parts punctuation marks. So now you can write:

Il répondit: «Ce pain coûte-t-il 2~€?»

The non-breaking space before the euro symbol is still necessary because currency symbols and other units or not supported in general (that's not specific to French).

You can use the numprint package along Babel. It will let you print numbers the French way.

\usepackage[autolanguage]{numprint} % Must be loaded *after* babel.

% ...

\nombre{123456.123456 e-17}

You will also notice that the layout of lists changes when switching to the French language. This is customizable using the \frenchbsetup command. For more information on what the frenchb option of babel does and how you can customize its behavior, run LaTeX on file frenchb.dtx and read the produced file frenchb.pdf or frenchb.dvi. You can get the PDF version on CTAN.


You can load German language support using either one of the two following commands.

For traditional ("old") German orthography use


or for reform ("new") German orthography use


This enables German hyphenation, if you have configured your LaTeX system accordingly. It also changes all automatic text into German, e.g. “Chapter” becomes “Kapitel”. A set of new commands also becomes available, which allows you to write German input files more quickly even when you don't use the inputenc package. Check out the table below for inspiration. With inputenc, all this becomes moot, but your text also is locked in a particular encoding world.

German Special Characters.
"A "O "U Ä Ö Ü
"a "o "u "s ä ö ü ß
"` or \glqq
"' or \grqq
\glq \grq
"< or \flqq «
"> or \frqq  »
\flq \frq ‹ ›
\dq "

In German books you sometimes find French quotation marks («guillemets»). German typesetters, however, use them differently. A quote in a German book would look like »this«. In the German speaking part of Switzerland, typesetters use «guillemets» the same way the French do. A major problem arises from the use of commands like \flq: If you use the OT1 font encoding (which is the default) the guillemets will look like the math symbol "", which turns a typesetter's stomach. T1 encoded fonts, on the other hand, do contain the required symbols. So if you are using this type of quote, make sure you use the T1 encoding.

Decimal numbers usually have to be written like 0{,}5 (not just 0,5). Packages like ziffer enable input like 0,5. Alternatively, one can use the \num command from the babel and (globally) set the decimal marker using

% ...


This is the preamble you need to write in the Greek language. Note the particular input encoding.


This preamble enables hyphenation and changes all automatic text to Greek. A set of new commands also becomes available, which allows you to write Greek input files more easily. In order to temporarily switch to English and vice versa, one can use the commands \textlatin{english text} and \textgreek{greek text} that both take one argument which is then typeset using the requested font encoding. Otherwise you can use the command \selectlanguage{...} described in a previous section. Use \euro for the Euro symbol.


Use the following lines:


More information in hungarian.

Icelandic and Faroese[edit]

The following lines can be added to write Icelandic text:


This changes text like Part into Hluti. It makes additional commands available:

Icelandic special commands
"` or \glqq
\th þ
\dh ð

To make special characters such as Þ and Æ become available just add:


The default LATEX font encoding is OT1, but it contains only the 128 characters. The T1 encoding contains letters and punctuation characters for most of the European languages using Latin script.


Italian is well supported by LaTeX. Just add


at the beginning of your document and the output of all the commands will be translated properly.


There is a variant of TeX intended for Japanese named pTeX, which supports vertical typesetting.

Another possible way to write in japanese is to use Lualatex and the luatex-ja package. Adapted example from the Luatexja documentation :

\usepackage{luatexja} % This line is unnecessary when using ltjclasses or ltjsclasses.

You can also use capabilities provided by the Fontspec package and those provided by Luatexja-fontspec to declare the font you want to use in your paper. Let us take an example :

% **********************************
% Basic setup
\usepackage{luatextra}%this package calls fontspec, luatexbase, lualibs, metalogo, luacode and fixltx2e
\setmainfont[Ligatures=Rare,Numbers=OldStyle]{Arno Pro} %setup of western font
\usepackage{luatexja-fontspec}%needed to call \setmainjfont bellow
\setmainjfont[BoldFont=KozGoPr6N-Bold]{KozGoPr6N-Regular} %setup of japanese font
It is a test to show japanese and english mix. テスト中です。どうですか皆さん。

Use UTF-8 as your encoding. In case you don't know how to do this, take a look at Texmaker, a LaTeX editor which use UTF-8 by default.

Another (but old) possible Japanese support is made available thanks to the CJK package collection. If you are using a package manager or a portage tree, the CJK collection is usually in a separate package because of its size (mainly due to fonts).

Make sure your document is saved using the UTF-8 character encoding. See Special Characters for more details. Put the parts where you want to write japanese characters in a CJK environment.



You can mix latin letters as well as hiragana, katakana and kanji.


The last argument specifies the font. It must fit the desired language, since fonts are different for Chinese, Japanese and Korean. min is an example for Japanese.


The two most widely used encodings for Korean text files are EUC-KR and its upward compatible extension used in Korean MS-Windows, CP949/Windows-949/UHC. In these encodings each US-ASCII character represents its normal ASCII character similar to other ASCII compatible encodings such as ISO-8859-x, EUC-JP, Big5, or Shift_JIS. On the other hand, Hangul syllables, Hanjas (Chinese characters as used in Korea), Hangul Jamos, Hiraganas, Katakanas, Greek and Cyrillic characters and other symbols and letters drawn from KS X 1001 are represented by two consecutive octets. The first has its MSB set. Until the mid-1990's, it took a considerable amount of time and effort to set up a Korean-capable environment under a non-localized (non-Korean) operating system. You can skim through the now much-outdated to get a glimpse of what it was like to use Korean under non-Korean OS in mid-1990's.

TeX and LaTeX were originally written for scripts with no more than 256 characters in their alphabet. To make them work for languages with considerably more characters such as Korean or Chinese, a subfont mechanism was developed. It divides a single CJK font with thousands or tens of thousands of glyphs into a set of subfonts with 256 glyphs each.

For Korean, there are three widely used packages.

  • HLATEX by UN Koaunghi
  • hLATEXp by CHA Jaechoon
  • the CJK package by Werner Lemberg

HLATEX and hLATEXp are specific to Korean and provide Korean localization on top of the font support. They both can process Korean input text files encoded in EUC-KR. HLATEX can even process input files encoded in CP949/Windows-949/UHC and UTF-8 when used along with Λ, Ω.

The CJK package is not specific to Korean. It can process input files in UTF-8 as well as in various CJK encodings including EUC-KR and CP949/Windows-949/UHC, it can be used to typeset documents with multilingual content (especially Chinese, Japanese and Korean). The CJK package has no Korean localization such as the one offered by HLATEX and it does not come with as many special Korean fonts as HLATEX.

The ultimate purpose of using typesetting programs like TeX and LaTeX is to get documents typeset in an aesthetically satisfying way. Arguably the most important element in typesetting is a set of welldesigned fonts. The HLATEX distribution includes UHC PostScript fonts of 10 different families and Munhwabu fonts (TrueType) of 5 different families. The CJK package works with a set of fonts used by earlier versions of HLATEX and it can use Bitstream's cyberbit True-Type font.

To use the HLATEX package for typesetting your Korean text, put the following declaration into the preamble of your document:


This command turns the Korean localization on. The headings of chapters, sections, subsections, table of content and table of figures are all translated into Korean and the formatting of the document is changed to follow Korean conventions. The package also provides automatic particle selection. In Korean, there are pairs of post-fix particles grammatically equivalent but different in form. Which of any given pair is correct depends on whether the preceding syllable ends with a vowel or a consonant. (It is a bit more complex than this, but this should give you a good picture.) Native Korean speakers have no problem picking the right particle, but it cannot be determined which particle to use for references and other automatic text that will change while you edit the document. It takes a painstaking effort to place appropriate particles manually every time you add/remove references or simply shuffle parts of your document around. HLATEX relieves its users from this boring and error-prone process.

In case you don't need Korean localization features but just want to typeset Korean text, you can put the following line in the preamble, instead.


For more details on typesetting Korean with HLATEX, refer to the HLATEX Guide. Check out the web site of the Korean TeX User Group (KTUG).

In the FAQ section of KTUG it is recommended to use the kotex package


Persian script[edit]

For Persian language, there is a dedicated package called XePersian which uses XeLaTeX as the typesetting engine. Just add the following code to your preamble:


See XePersian page on CTAN

Moreover, Arabic script can be used to type Persian as illustrated in the corresponding section.


If you plan to use Polish in your UTF-8 encoded document, use the following code


The above code merely allows to use Polish letters and translates the automatic text to Polish, so that "chapter" becomes "rozdział". There are a few additional things one must remember about.


Polish has many single letter connectives: "a", "o", "w", "i", "u", "z", etc., grammar and typography rules don't allow for them to end a printed line. To ensure that LaTeX won't set them as last letter in the line, you have to use non breakable space:

Noc była sierpniowa, ciepła i~słodka, Księżyc oświecał srebrnem światłem wgłębienie, tak,
że twarze małego rycerza i~Basi były skąpane w blasku.
Poniżej, na podwórzu zamkowem, widać było uśpione kupy żołnierzy, a~także i~ciała zabitych
podczas dziennej strzelaniny, bo nie znaleziono dotąd czasu na ich pogrzebanie.


According to Polish grammar rules, you have to put dots after numerals in chapter, section, subsection, etc. headers.

This is achieved by redefining few LaTeX macros.

For books:


For articles:


Alternatively you can use dedicated document classes:

  • the mwart class instead of article,
  • mwbk instead of book
  • and mwrep instead of report.

Those classes have much more European typography settings but do not require the use of Polish babel settings or character encoding.

Simple usage:

Pójdź kińże tę chmurność w głąb flaszy.

Full documentation for those classes is available at (Polish).


It may be customary (depending on publisher) to indent the first paragraph in sections and chapters:


Hyphenation and typography[edit]

It's much more frowned upon to set pages with hyphenation between pages than it is customary in American typesetting.

To adjust penalties for hyphenation spanning pages, use this command:


To adjust penalties for leaving widows and orphans (clubs in TeX nomenclature) use those commands:


Commas in math[edit]

According to some typography rules, fractional parts of numbers should be delimited by a comma, not a dot. To make LaTeX not insert additional space in math mode after a comma (unless there is a space after the comma), use the icomma package.


Unfortunately, it is partially incompatible with the dcolumn package. One needs to either use dots in columns with numerical data in the source file and make dcolumn switch them to commas for display or define the column as follows:

\begin{tabular}{... D{,}{\mathord\mathcomma}{2} ...}

The alternative is to use the numprint package, but it is much less convenient.

Another alternative is using package siunitx that lets you typeset numbers and their according units consistently. Number alignment in tables and different output modes re supported.

Further information[edit]

Refer the Słownik Ortograficzny (in Polish) for additional information on Polish grammar and typography rules.

Good extract is available at Zasady Typograficzne Składania Tekstu (in Polish).


Add the following code to your preamble:


You can substitute the language for brazilian portuguese by choosing brazilian or brazil.


Basic settings are fine when left the same as Czech, but Slovak needs special signs for 'ď', 'ť', 'ľ'. To be able to type them from keyboard use the following settings:



Include the appropriate Babel option:


The trick is that Spanish has several options and commands to control the layout. The options may be loaded either at the call to Babel, or before, by defining the command \spanishoptions. Therefore, the following commands are roughly equivalent:


On average, the former syntax should be preferred, as the latter is a deviation from standard Babel behavior, and thus may break other programs (LyX, latex2rtf) interacting with LaTeX.

Spanish also defines shorthands for the dot and << >> so that they are used as logical markup: the former is used as decimal marker in math mode, and the output is typically either a comma or a dot; the latter is used for quoted text, and the output is typically either «» or “”. This allows different typographical conventions with the same input, as preferences may be quite different from, say, Spain and Mexico.

Two particularly useful options are es-noquoting,es-nolists: some packages and classes are known to collide with Spanish in the way they handle active characters, and these options disable the internal workings of Spanish to allow you to overcome these common pitfalls. Moreover, these options may simplify the way LyX customizes some features of the Spanish layout from inside the GUI.

The options mexico,mexico-com provide support for local custom in Mexico: the former using decimal dot, as customary, and the latter allowing decimal comma, as required by the Mexican Official Norm (NOM) of the Department of Economy for labels in foods and goods. More localizations are in the making.

The other commands modify the spanish layout after loading Babel. Two particularly useful commands are \spanishoperators and \spanishdeactivate.

The macro \spanishoperators{<list of operators>}{ contains a list of spanish mathematical operators, and may be redefined at will. For instance, the command


only defines sen, overriding all other definitions; the command \let\spanishoperators\relax disables them all. This command supports accented or spaced operators: the \acute{<letter>} command puts an accent, and the \, command adds a small space. For instance, the following operators are defined by default.

l\acute{i}m l\acute{i}m\,sup l\acute{i}m\,inf m\acute{a}x 
\acute{i}nf m\acute{i}n sen tg arc\,sen arc\,cos arc\,tg 
cotg cosec senh tgh

Finally, the macro \spanishdeactivate{<list of characters>} disables some active characters, to keep you out of trouble if they are redefined by other packages. The candidates for deactivation are the set {<>."'}. Please, beware that some option preempt the availability of some active characters. In particular, you should not combine the es-noquoting option with \spanishdeactivate{<>}, or the es-noshorthands with \spanishdeactivate{<>."}.

Please check the documentation for Babel or spanish.dtx for further details.


One option to use Tibetan script in LaTeX is to add


to your preamble and use a slightly modified Wylie transliteration for input. Refer to the excellent package documentation for details. More information can be found on [9]


  1. The Not So Short Introduction to LaTeX, 2.5.6 Support for Cyrillic, Maksym Polyakov
  2. The Not So Short Introduction to LaTeX, Bulgarian translation
  3. babel-french documentation: "the French language should now be loaded as french, not as frenchb or francais and preferably as a global option of \documentclass. Some tolerance still exists in v3.0, but do not rely on it."


The rotating package[edit]

The package rotating gives you the possibility to rotate any object of an arbitrary angle. Once you have loaded it with the standard command in the preamble:


you can use three new environments:


it will rotate the whole argument by 90 degrees counterclockwise. Moreover:


it will turn the argument of 30 degrees. You can give any angle as an argument, whether it is positive or negative. It will leave the necessary space to avoid any overlapping of text.


like turn, but it will not add any extra space.

If you want to make a float sideways so that the caption is also rotated, you can use




Note, though, they will be placed on a separate page.

If you would like to rotate a TikZ picture you could use sideways together with minipage.


You can also use the \rotatebox command. Let's rotate a tabular inside a table for example:



Default is sidewaysfigures/sidewaystables are oriented depending on page number in two sided documents (takes two passes).

The rotating package takes the following options.

In single sided documents turn sidewaysfigures/sidewaystables counterclockwise.
In single sided documents turn sidewaysfigures/sidewaystables clockwise (default).
In two sided documents all sidewaysfigures/sidewaystables are same orientation (left of figure, table now bottom of page). This is the style preferred by the Chicago Manual of Style (broadside).
In two sided documents all sidewaysfigures/sidewaystables are same orientation (left of figure, table now at top of page).

The rotfloat package[edit]

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


just like for normal tables. The H option can not be used without this package.


Tables are a common feature in academic writing, often used to summarize research results. Mastering the art of table construction in LaTeX is therefore necessary to produce quality papers and with sufficient practice one can print beautiful tables of any kind.

Keeping in mind that LaTeX is not a spreadsheet, it makes sense to use a dedicated tool to build tables and then to export these tables into the document. Basic tables are not too taxing, but anything more advanced can take a fair bit of construction; in these cases, more advanced packages can be very useful. However, first it is important to know the basics. Once you are comfortable with basic LaTeX tables, you might have a look at more advanced packages or the export options of your favorite spreadsheet. Thanks to the modular nature of LaTeX, the whole process can be automated in a fairly comfortable way.

For a long time, LaTeX tables were quite a chaotic topic, with dozens of packages doing similar things, while not always being compatible with one another. Sometimes you had to make trade-offs. The situation changed recently (2010) with the release of the tabu package which combines the power of longtable, tabularx and much more. The tabu environment is far less fragile and restricted than the older alternatives. Nonetheless, before attempting to use this package for the first time it will be beneficial to understand how the classic environment works, since tabu works the same way. Note however that the author of tabu will not fix bugs to the current version, and that the next version introduces new syntax that will likely break existing documents.[1]

The tabular environment[edit]

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 list in chapter Lengths.

The optional parameter pos can be used to specify the vertical position of the table relative to the baseline of the surrounding text. In most cases, you will not need this option. It becomes relevant only if your table is not in a paragraph of its own. You can use the following letters:

b bottom
c center (default)
t top

To specify a font format (such as bold, italic, etc.) for an entire column, you can add >{\format} before you declare the alignment. For example \begin{tabular}{ >{\bfseries}l c >{\itshape}r } will indicate a three column table with the first one aligned to the left and in bold font, the second one aligned in the center and with normal font, and the third aligned to the right and in italic. The "array" package needs to be activated in the preamble for this to work.

In the first line you have pointed out how many columns 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
\newline start a new line within a cell (in a paragraph column)
\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 one's preferences. I personally add spaces between to make it easier to read.

Basic examples[edit]

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 \\

Expanding upon that by including some vertical lines:

\begin{tabular}{ l | c | r }
  1 & 2 & 3 \\
  4 & 5 & 6 \\
  7 & 8 & 9 \\

To add horizontal lines to the very top and bottom edges of the table:

\begin{tabular}{ l | c | r }
  1 & 2 & 3 \\
  4 & 5 & 6 \\
  7 & 8 & 9 \\

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{tabular}{ l | c | r }
    1 & 2 & 3 \\ \hline
    4 & 5 & 6 \\ \hline
    7 & 8 & 9 \\

  \begin{tabular}{ | l | c | r }
    1 & 2 & 3 \\ \hline
    4 & 5 & 6 \\ \hline
    7 & 8 & 9 \\

  7C0 & hexadecimal \\
  3700 & octal \\ \cline{2-2}
  11111000000 & binary \\
  \hline \hline
  1984 & decimal \\

Latex example tabular cline.svg

Text wrapping in tables[edit]

LaTeX's algorithms for formatting tables have a few shortcomings. One is that it will not automatically wrap text in cells, even if it overruns the width of the page. For columns that will contain text whose length exceeds the column's width, it is recommended that you use the p attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). For a more convenient method, have a look at The tabularx package, or The tabulary package.

Instead of p, use the m attribute to have the lines aligned toward the middle of the box or the b attribute to align along the bottom of the box.

Here is a simple 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:



Without specifying width for last column:
    \begin{tabular}{| l | l | l | l |}
    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. \\

With width specified:
    \begin{tabular}{ | l | l | l | p{5cm} |}
    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. \\


You get the following output:

Latex example wrapped table.svg

Note that the first table has been cropped, since the output is wider than the page width.

Manually broken paragraphs in table cells[edit]

Sometimes it is necessary to not rely on the breaking algorithm when using the p specifier, but rather specify the line breaks by hand. In this case it is easiest to use a \parbox:

  boring cell content & \parbox[t]{5cm}{rather long par\\new par}

Here the t argument controls the placement of the text inside the box. Other allowed values are c for center and b for bottom.

Space between columns[edit]

To tweak the space between columns (LaTeX will by default choose very tight columns), one can alter the column separation: \setlength{\tabcolsep}{5pt}. The default value is 6pt.

Space between rows[edit]

Re-define the \arraystretch command to set the space between rows:


Default value is 1.0.

An alternative way to adjust the rule spacing is to add \noalign{\smallskip} before or after the \hline and \cline{i-j} commands:

\begin{tabular}{ | l | l | r | }
  \multicolumn{2}{c}{Item} \\
  Animal & Description & Price (\$) \\
  Gnat  & per gram & 13.65 \\
        & each     &  0.01 \\
  Gnu   & stuffed  & 92.50 \\
  Emu   & stuffed  & 33.33 \\
  Armadillo & frozen & 8.99 \\

You may also specify the skip after a line explicitly using glue after the line terminator

Mineral & Color \\[1cm]
Ruby & red \\
Sapphire & blue \\

Other environments inside tables[edit]

If you use some LaTeX environments inside table cells, like verbatim or enumerate:

\begin{tabular}{c c}
	& description
 	\\ \hline

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[edit]

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:

Team              & P & W & D & L & F  & A & Pts \\
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 & 3 &  5 & 8 &  7  \\

Latex example defining multiple columns.svg

Column specification using >{\cmd} and <{\cmd}[edit]

The column specification can be altered using the array package. This is done in the argument of the tabular environment using >{\command} for commands executed right before each column element and <{\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 \textbf to produce bold text), one should use the \bgroup and \egroup commands: >{\textbf\bgroup}c<{\egroup} produces the intended effect. This works only for some basic LaTeX commands. For other commands, such as \underline to underline text, it is necessary to temporarily store the column text in a box using lrbox. First, you must define such a box with \newsavebox{\boxname} and then you can define:

>{\begin{lrbox}{\boxname} }%
  \underline{\unhbox\boxname} }%

This stores the text in a box and afterwards, takes the text out of the box with \unhbox (this destroys the box, if the box is needed again one should use \unhcopy instead) and passing it to \underline. (For LaTeX2e, you may want to use \usebox{\boxname} instead of \unhbox\boxname.)

This same trick done with \raisebox instead of \underline can force all lines in a table to have equal height, instead of the natural varying height that can occur when e.g. math terms or superscripts occur in the text.

Here is an example showing the use of both p{...} and >{\centering} :

\begin{tabular}{>{\centering}p{3.5cm}<{\centering}p{3.5cm} }
Geometry  & Algebra
 Points & Addition 
 Spheres & Multiplication 

Note the use of \tabularnewline instead of \\ to avoid a Misplaced \noalign error.


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:

  3   & 14159 \\
  16  & 2     \\
  123 & 456   \\

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| }
  stuff & stuff \\ \hline
  stuff & stuff \\








Aligning columns at decimal points using dcolumn[edit]

Instead of using @-expressions to build columns of decimals aligned to the decimal point (or equivalent symbol), it is possible to center a column on the decimal separator using the dcolumn package, which provides a new column specifier for floating point data. See the dcolumn package documentation for more information, but a simple way to use dcolumn is as follows.

\newcolumntype{d}[1]{D{.}{\cdot}{#1} }
%the argument for d specifies the maximum number of decimal places
\begin{tabular}{l r c d{1} }

LaTeX example dcolumn.png

A negative argument provided for the number of decimal places in the new column type allows unlimited decimal places, but may result in rather wide columns. Rounding is not applied, so the data to be tabulated should be adjusted to the number of decimal places specified. Note that a decimal aligned column is typeset in math mode, hence the use of \mathrm for the column heading in the example above. Also, text in a decimal aligned column (for example the header) will be right-aligned before the decimal separator (assuming there's no decimal separator in the text). While this may be fine for very short text, or numeric column headings, it looks cumbersome in the example above. A solution to this is to use the \multicolumn command described below, specifying a single column and its alignment. For example to center the header Decimal over its column in the above example, the first line of the table itself would be Left&Right&Center&\multicolumn{1}{c}{Decimal}\\

Bold text and dcolumn[edit]

To draw attention to particular entries in a table, it may be nice to use bold text. Ordinarily this is easy, but as dcolumn needs to see the decimal point it is rather harder to do. In addition, the usual bold characters are wider than their normal counterparts, meaning that although the decimals may align nicely, the figures (for more than 2--3 digits on one side of the decimal point) will be visibly misaligned. It is however possible to use normal width bold characters and define a new bold column type, as shown below.[2]

%here we're setting up a version of the math fonts with normal x-width
\SetSymbolFont{operators}{nxbold}{OT1}{cmr} {b}{n}
\SetSymbolFont{letters}  {nxbold}{OML}{cmm} {b}{it}
\SetSymbolFont{symbols}  {nxbold}{OMS}{cmsy}{b}{n}

\newcolumntype{d}{D{.}{.}{-1} } %decimal column as before
%wide bold decimal column
\newcolumntype{B}[3]{>{\boldmath\DC@{#1}{#2}{#3} }c<{\DC@end} } 
%normal width bold decimal column
\newcolumntype{Z}[3]{>{\mathversion{nxbold}\DC@{#1}{#2}{#3} }c<{\DC@end} } 
\begin{tabular}{l l d}
    Type &M & \multicolumn{1}{c}{N} \\
    Normal & 1 & 22222.222 \\
    Bold (standard)&10 & \multicolumn{1}{B{.}{.}{-1} }{22222.222}\\
    Bold (nxbold)&100 & \multicolumn{1}{Z{.}{.}{-1} }{22222.222}\\

LaTeX example dcolumn bold.png

Row specification[edit]

It might be convenient to apply the same command over every cell of a row, just as for column. Unfortunately the tabular environment cannot do that by default. We will need tabu instead, which provides the \rowfont option.

\rowfont{\bfseries\itshape\large} Header1 & Header2 \\
Cell2 & Cell2


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[edit]

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 specify 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| }
  \multicolumn{2}{|c|}{Team sheet} \\
  GK & Paul Robinson \\
  LB & Lucas Radebe \\
  DC & Michael Duberry \\
  DC & Dominic Matteo \\
  RB & Dider Domi \\
  MC & David Batty \\
  MC & Eirik Bakke \\
  MC & Jody Morris \\
  FW & Jamie McMaster \\
  ST & Alan Smith \\
  ST & Mark Viduka \\


Columns spanning multiple rows[edit]

The first thing you need to do is add \usepackage{multirow} to the preamble[3]. 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 content's natural width).


\begin{tabular}{ |l|l|l| }
\multicolumn{3}{ |c| }{Team sheet} \\
Goalkeeper & GK & Paul Robinson \\ \hline
\multirow{4}{*}{Defenders} & LB & Lucas Radebe \\
 & DC & Michael Duburry \\
 & 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 \\


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 columns, there must always be ampersands in each row (unless \multicolumn is also used).

Spanning in both directions simultaneously[edit]

Here is a nontrivial example of how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:


& & \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}


The command \multicolumn{1}{ 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}{ 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".

Here is another example exploiting the same ideas to make the familiar and popular "2x2" or double dichotomy:

\begin{tabular}{ r|c|c| }
 &  \multicolumn{1}{c}{noninteractive}
 & \multicolumn{1}{c}{interactive} \\
massively multiple & Library & University \\
one-to-one & Book & Tutor \\


Controlling table size[edit]

Resize tables[edit]

The graphicx packages features the command \resizebox{width}{height}{object} which 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}{!} {

Resizing table including the caption

& \multicolumn{1}{c}{noninteractive}
& \multicolumn{1}{c}{interactive} \\
massively multiple & Library & University \\
one-to-one & Book & Tutor \\
\caption[Table caption text]{Table taken from \cite[p.10]{refid} }
\end{minipage} }

Alternatively you can use \scalebox{ratio}{object} in the same way but with ratios rather than fixed sizes:

% ...


Changing font size[edit]

A table can be globally switched to a different font size by simply adding the desired size command (here: \footnotesize) in the table scope, which may be after the \begin{table} statement if you use floats, otherwise you need to add a group delimiter.

  \begin{tabular}{| r | r || c | c | c |}
      % ...
  \caption{Performance at peak F-measure}
  \begin{tabular}{| r | r || c | c | c |}
      % ...

Alternatively, you can change the default font for all the tables in your document by placing the following code in the preamble:


See Fonts for named font sizes. The table caption font size is not affected. To control the caption font size, see Caption Styles.


Alternate row colors in tables[edit]

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.





odd 	& odd 	& odd \\
even 	& even 	& even\\
odd 	& odd 	& odd \\
even 	& even 	& even\\


The command \hiderowcolors is available to deactivate highlighting from a specified row until the end of the table. Highlighting can be reactivated within the table via the \showrowcolors command. If while using these commands you experience "misplaced \noalign errors" then use the commands at the very beginning or end of a row in your tabular.

\hiderowcolors odd & odd & odd \\


odd & odd & odd \\ \showrowcolors

Colors of individual cells[edit]

As above this uses the xcolor package.

% Include this somewhere in your document

% Enter this in the cell you wish to color a light grey.
% NB: the word 'gray' here denotes the grayscale color scheme, not the color grey. '0.9' denotes how dark the grey is.
% The following will color the cell red.

Width and stretching[edit]

We keep providing documentation for tabular* and tabularx although they are completely eclipsed by the much more powerful and flexible tabu environment. Actually tabu is greatly inspired by those environments, so it may be worth it to have an idea how they work, particularly for tabularx.

The tabular* environment[edit]

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 | }
  label 1 & label 2 & label 3 & label 4 \\
  item 1  & item 2  & item 3  & item 4  \\
LaTeX TabWidth1.svg

However, that may not look quite as intended. The columns are still at their natural width (just wide enough to fit their contents) while the rows are as wide as the table width specified. If you do not like this default, you must also explicitly insert extra column space. LaTeX has rubber lengths, which, unlike others, are not fixed. LaTeX can dynamically decide how long the lengths should be. So, an example of this is the following.

\begin{tabular*}{0.75\textwidth}{@{\extracolsep{\fill} } | c | c | c | r | }
  label 1 & label 2 & label 3 & label 4 \\
  item 1  & item 2  & item 3  & item 4  \\
LaTeX TabWidth2.svg

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[edit]

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.

% ...

\begin{tabularx}{\textwidth}{ |X|X|X|X| }
  label 1 & label 2 & label 3 & label 4 \\
  item 1  & item 2  & item 3  & item 4  \\
LaTeX TabXWidth1.svg

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 to use \newcolumntype to format selected columns 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):

% ...

\begin{tabularx}{\textwidth}{ |l|R|l|R| }
  label 1 & label 2 & label 3 & label 4 \\
  item 1  & item 2  & item 3  & item 4  \\
LaTeX TabXWidth2.svg

Tabularx with rows spanning multiple columns using \multicolumn. The two central columns are posing as one by using the X@{} option. Note that the \multicolumn width (which in this example is 2) should equal the (in this example 1+1) width of the spanned columns:

% ...

\begin{tabularx}{1\textwidth}{ |>{\setlength\hsize{1\hsize}\centering}X|>{\setlength\hsize{1\hsize}\raggedleft}X@{} >{\setlength\hsize{1\hsize}\raggedright}X|>{\setlength\hsize{1\hsize}\centering}X| } 
Label 1 & \multicolumn{2}{>{\centering\setlength\hsize{2\hsize} }X|}{Label 2} & Label 3\tabularnewline
  123  & 123  & 456  & 123  \tabularnewline
  123  & 123  & 456  & 123  \tabularnewline
LaTeX tabularx multi.svg

In a way analogous to how new commands with arguments can be created with \newcommand, new column types with arguments can be created with \newcolumntype as follows:

\usepackage[table]{xcolor} %Used to color the last column
% ...


\begin{tabularx}{\textwidth}{ | L{1} | R{0.5} | R{0.5} | C{2}{gray} | }
  label 1 & label 2 & label 3 & label 4 \\
  item 1  & item 2  & item 3  & item 4  \\

where since there are 4 columns, the sum of the \hsize's (1 + 0.5 + 0.5 + 2) must be equal to 4. The default value used by tabularx for \hsize is 1.

The tabulary package[edit]

tabulary is a modified tabular* allowing width of columns set for equal heights. tabulary allows easy and convenient writing of well balanced tables.

The problem with tabularx is that it leaves much blank if your cells are almost empty. Besides, it is not easy to have different column sizes.

tabulary tries to balance the column widths so that each column has at least its natural width, without exceeding the maximum length.


    Short sentences      & \#  & Long sentences                                                 \\
    This is short.       & 173 & This is much loooooooonger, because there are many more words.  \\
    This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\

The first parameter is the maximum width. tabulary will try not to exceed it, but it will not stretch to it if there is not enough content, contrary to tabularx.

The second parameter is the column disposition. Possible values are those from the tabular environment, plus

L left-justified balanced column
C centered balanced column
R right-justified balanced column
J left-right-justified balanced column

These are all capitals.

The tabu environment[edit]

It works pretty much like tabularx.

\begin{tabu} to \linewidth {llX[2]lllXl}
% ...

to \linewidth specifies the target width. The X parameter can have an optional span factor.

Table across several pages[edit]

Long tables are natively supported by LaTeX thanks to the longtable environment. Unfortunately this environment does not support stretching (X columns).

The tabu packages provides the longtabu environment. It has most of the features of tabu, with the additional capability to span multiple pages.

LaTeX can do well with long tables: you can specify a header that will repeat on every page, a header for the first page only, and the same for the footer.

\begin{longtabu} to \linewidth {lX[2]lXl}

\rowfont\bfseries H1 & H2 & H3 & H4 & H5 \\ \hline 

\\ \hline
\multicolumn{5}{r}{There is more to come} \\

\\ \hline

% Content ...

It uses syntax similar to longtable, so you should have a look at its documentation if you want to know more.

Alternatively you can try one of the following packages supertabular or xtab, an extended and somewhat improved version of supertabular.

Partial vertical lines[edit]

Adding a partial vertical line to an individual cell:

\begin{tabular}{ l c r }
  1 & 2 & 3 \\ \hline
  4 & 5 & \multicolumn{1}{r|}{6}  \\ \hline
  7 & 8 & 9 \\ \hline


Removing part of a vertical line in a particular cell:

\begin{tabular}{ | l | c | r | }
  1 & 2 & 3 \\ \hline
  4 & 5 & \multicolumn{1}{r}{6} \\ \hline
  7 & 8 & 9 \\ \hline


Vertically centered images[edit]

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} }

A raisebox works as well, also allowing to manually fine-tune the alignment with its first parameter.

\raisebox{-.5\height}{\includegraphics{image.png} }

Footnotes in tables[edit]

The tabular environment does not handle footnotes properly. The longtabular fixes that.

Instead of using longtabular we recommend tabu which handles footnotes properly, both in normal and long tables.

Professional tables[edit]

Many 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 two equivalent normal LaTeX implementations (the second example requires \usepackage{array} or \usepackage{dcolumn}, and the third example requires \usepackage{booktabs} in the preamble).

Normal LaTeX[edit]

\multicolumn{2}{c}{Item} \\
Animal    & Description & Price (\$) \\
Gnat      & per gram    & 13.65      \\
          & each        & 0.01       \\
Gnu       & stuffed     & 92.50      \\
Emu       & stuffed     & 33.33      \\
Armadillo & frozen      & 8.99       \\

LaTeX animal table.svg

Using array[edit]

%or \usepackage{dcolumn}
\multicolumn{2}{c}{Item} \\
Animal    & Description & Price (\$) \\
Gnat      & per gram    & 13.65      \\
          & each        & 0.01       \\
Gnu       & stuffed     & 92.50      \\
Emu       & stuffed     & 33.33      \\
Armadillo & frozen      & 8.99       \\

LaTeX animal table with array.svg

Using booktabs[edit]

\multicolumn{2}{c}{Item} \\
Animal    & Description & Price (\$) \\
Gnat      & per gram    & 13.65      \\
          &    each     & 0.01       \\
Gnu       & stuffed     & 92.50      \\
Emu       & stuffed     & 33.33      \\
Armadillo & frozen      & 8.99       \\

LaTeX animal table with booktabs.svg

Usually the need arises for footnotes under a table (and not at the bottom of the page), with a caption properly spaced above the table. These are addressed by the ctable package. It provides the option of a short caption given to be inserted in the list of tables, instead of the actual caption (which may be quite long and inappropriate for the list of tables). The ctable uses the booktabs package.

Sideways tables[edit]

Tables can also be put on their side within a document using the rotating or the rotfloat package. See the Rotations chapter.

Table with legend[edit]

To add a legend to a table the caption package can be used. With the caption package a \caption*{...} statement can be added besides the normal \caption{...}. Example:

  \begin{tabular}{| r | r || c | c | c |}


  \caption{A normal caption}
    A legend, even a table can be used
    \begin{tabular}{l l}
      item 1 & explanation 1 \\

The normal caption is needed for labels and references.

The eqparbox package[edit]

On rare occasions, it might be necessary to stretch every row in a table to the natural width of its longest line, for instance when one has the same text in two languages and wishes to present these next to each other with lines synching up. A tabular environment helps control where lines should break, but cannot justify the text, which leads to ragged right edges. The eqparbox package provides the command \eqmakebox which is like \makebox but instead of a width argument, it takes a tag. During compilation it bookkeeps which \eqmakebox with a certain tag contains the widest text and can stretch all \eqmakeboxes with the same tag to that width. Combined with the array package, one can define a column specifier that justifies the text in all lines:

  >{\begin{lrbox}{\tstretchbox} }%
  \eqmakebox[#1][s]{\unhcopy\tstretchbox} }%

See the documentation of the eqparbox package for more details.

Floating with table[edit]

In WYSIWYG document processors, it is common to put tables in the middle of the text. This is what we have been doing until now. Professional documents, however, often make it a point to print tables on a dedicated page so that they do not disrupt the flow. From the point of view of the source code, one has no idea on which page the current text is going to lie, so it is hardly possible to guess which page may be appropriate for our table. LaTeX can automate this task by abstracting objects such as tables, pictures, etc., and deciding for us where they might fit best. This abstraction is called a float. Generally, an object that is floated will appear in the vicinity of its introduction in the source file, but one can choose to control its position also.

To tell LaTeX we want to use our table as a float, we need to put a table environment around the tabular environment, which is able to float and add a label and caption.

The table environment initiates a type of float just as the environment figure. In fact, the two bear a lot of similarities (positioning, captions, etc.). More information about floating environments, captions etc. can be found in Floats, Figures and Captions.

The environment names may now seem quite confusing. Let's sum it up:

  • tabular is for the content itself (columns, lines, etc.).
  • table is for the location of the table on the document, plus caption and label support.
\begin{table}[position specifier]
    ... your table ...
  \caption{This table shows some data}

In the table, we used a label, so now we can refer to it just like any other reference:


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


The captions now show up in the list of tables, if displayed.

You can set the optional parameter position specifier to define the position of the table, where it should be placed. The following characters are all possible placements. Using sequences of it define your "wishlist" to LaTeX.

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.

Default is tbp, which means that it is by default placed on the top of the page. If that's not possible, it's placed at the bottom if possible, or finally with other floating environments on an extra page.

You can force LaTeX to use one given position. E.g. [!h] forces LaTeX to place it exactly where you place it (Except when it's really impossible, e.g you place a table here and this place would be the last line on a page). Again, understand it correctly: it urges LaTeX to put the table at a specific place, but it will not be placed there if LaTeX thinks it will not look great. If you really want to place your table manually, do not use the table environment.

Centering the table horizontally works like everything else, using the \centering command just after opening the table environment, or by enclosing it with a center environment.

Using spreadsheets and data analysis tools[edit]

For complex or dynamic tables, you may want to use a spreadsheet. You might save lots of time by building tables using specialized software and exporting them in LaTeX format. The following plugins and libraries are available for some popular software:

However, copying the generated source code to your document is not convenient at all. For maximum flexibility, generate the source code to a separate file which you can input from your main document file with the \input command. If your speadsheet supports command-line, you can generate your complete document (table included) in one command, using a Makefile for example.

See Modular Documents for more details.

Need more complicated features?[edit]

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
  • threeparttable makes it possible to put footnotes both within the table and its caption
  • arydshln: creates dashed horizontal and vertical lines
  • ctable: allows for footnotes under table and properly spaced caption above (incorporates booktabs package)
  • slashbox: create 2D tables with the first cell containing a description for both axes. Not available in Tex Live 2011 or later.
  • diagbox: compatible to slashbox, come with Tex Live 2011 or later
  • dcolumn: decimal point alignment of numeric cells
  • rccol: advanced decimal point alignment of numeric cells with rounding
  • numprint: print numbers, in the current mode (text or math) in order to use the correct font, with separators, exponent and/or rounded to a given number of digits. tabular(*), array, tabularx, and longtable environments are supported using all features of numprint
  • spreadtab: spread sheets allowing the use of formulae
  • siunitx: alignment of tabular entries
  • pgfplotstable: Loads, rounds, formats and postprocesses numerical tables.


Title creation[edit]

For 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. We will detail the process here.

There are several situations where you might want to create a title in a custom format, rather than in the format natively supported by LaTeX classes. 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, and this section will show you how to accomplish this.

Standard Titles[edit]

Many document classes will form a title or a title page for you. One must specify what to fill it with using these commands placed in the top matter:

\title{The Triangulation of Titling Data in Non-Linear Gaussian Fashion via $\rho$ Series}
\date{October 31, 2014}
\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 omitted in the source file.

To form a title, use


This should go after the preceding commands after beginning the document. For most document classes, this will form a separate page, while the article document class will place the title on the top of the first page. If you want to have a separate title page for articles as well, use the documentclass option titlepage 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.

It is dependent on the document class which commands are used in the title generated by \maketitle. Referring to the documentation will lead to trusted information.

The title for journal submission[edit]

Journals follow a specific layout. To ensure this they often provide a template which defines the layout. What is available for the title (for example emails, affiliation names, keywords) heavily depends on the template and highly differs between different journals. Follow the template if the journal provides one. If they don't you should use the most basic concepts of LaTeX titles described above.

Create a custom title for a report or book[edit]

The title page of a book or a report is the first thing a reader will see. Keep that in mind when preparing your title page.

You need to know very basic LaTeX layout commands in order to get your own title page perfect. Usually a custom titlepage does not contain any semantic markup, everything is hand crafted. Here are some of the most often needed things:


if you want to center some text just use \centering. If you want to align it differently you can use the environment \raggedleft for right-alignment and \raggedright for left-alignment.


the command for including images (a logo for example) is the following : \includegraphics[width=0.15\textwidth]{./logo}. There is no \begin{figure} as you would usually use since you don't want it to be floating, you just want it exactly where want it to be. 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 braces, {like this}, and you can use the following commands (in order of size): \Huge, \huge, \LARGE, \Large, \large, \normalsize, \small, \footnotesize, \tiny. So for example:

{\large this text is slightly bigger than normal}, this one is not.

Remember, if you have a block of text in a different size, even if it is a bit of text on a single line, end it with \par.

Filling the page 

the command \vfill as the last item of your content will add empty space until the page is full. If you put it within the page, you will ensure that all the following text will be placed at the bottom of the page.

A practical example[edit]

All these tips might have made you confused. Here is a practical and compilable example. The picture in use comes with package mwe and should be available with every complete LaTeX installation. You can start testing right away.

	{\scshape\LARGE Columbidae University \par}
	{\scshape\Large Final year project\par}
	{\huge\bfseries Pigeons love doves\par}
	{\Large\itshape John Birdwatch\par}
	supervised by\par
	Dr.~Mark \textsc{Brown}


% Bottom of the page
	{\large \today\par}

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 fonts it gets even more complicated, 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.

The result is shown below


Integrating the title page[edit]

A title page for a book or a report to get a university degree {Bachelor, Master, Ph.D., etc.) is quite static, it doesn't really change over time. You can prepare the titlepage in its own little document and prepare a one page pdf that you later include into your real document. This is really useful, if the title page is required to have completely different margins compared to the rest of the document. It also saves compile time, though it is not much.

Assuming you have done the title page of your report in an extra document, let's pretend it is called reportTitlepage2016.pdf, you can include it quite simply. Here is a short document setup.

\chapter{Introducing birds}

A title to be re-used multiple times[edit]

Some universities, departments and companies have strict rules how a title page of a report should look like. To ensure the very same output for all reports, a redefiniton of the \maketitle command is recommended.

This is best done by an experienced LaTeX user. A simple example follows, as usual there is no real limit with respect to complexity.

As a starting point, a LaTeX package called columbidaeTitle.sty is generated that defines the complete title matter. It will later be hidden from the end user. Ideally, the person creating the package should maintain it for a long time, create an accompanying documentation and ensure user support.

% Copyright note: This package defines how titles should
% be typeset at the columbidae University
% Please check for updates
\ProvidesPackage{columbidaeTitle}[2015/08/10 v.01 an
example package^^J for wikibooks]
\newcommand*{\@project}{Final Year Project}
\newcommand*{\@supervisor}{\texttt{\string\supervisor} currently
not set. Please fix this.}
{\scshape\LARGE Columbidae University \par}
supervised by\par


{\large \@date\par}

This package can be loaded within a usual document. The user can set the variables for title and the like. Which commands are actually available, and which might be omissible should be written in a documentation that is bundled with the package.

Look around what happens if you leave one or the other command out.

%\supervisor{Dr. James Miller}
\project{Bachelor Thesis}
\author{A LaTeX enthusiast}
\title{Why i want to be a duck}
\chapter{Ducks are awesome}

Packages for custom titles[edit]

The titling package[1] provides control over the typesetting of the \maketitle and \thanks commands. It is useful for small changes to the standard output.

Italian users may also want to use the frontespizio package[2]. It defines a frontispiece as used in Italia.

Package authblk The [3] provides new means to typeset the authors. This is especially helpful for journal submissions without an available template.

More titlepage examples[edit]

The titlepages package presents many different styles for title pages.

TeX.SE has a collection of titlepages.

Another small collection can be found on Github.

Notes and References[edit]

Page Layout[edit]

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.

We will often have to deal with TeX lengths in this chapter. You should have a look at Lengths for comprehensive details on the topic.

Two-sided documents[edit]

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. The most notable effect can be seen in page margins. If you want to make the article class two-sided, use \documentclass[twoside]{article}.

Many commands and variables in LaTeX take this concept into account. They are referred to as even and odd. For one-sided document, only the odd commands and variables will be in effect.

Page dimensions[edit]

A page in LaTeX is defined by many 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. All sizes are given in TeX points (pt), there are 72.27pt in an inch or 1pt ≈ 0.3515mm.

Latex layout.svg
  1. one inch + \hoffset
  2. one inch + \voffset
  3. \oddsidemargin = 31pt
  4. \topmargin = 20pt
  5. \headheight = 12pt
  6. \headsep = 25pt
  7. \textheight = 592pt
  8. \textwidth = 390pt
  9. \marginparsep = 10pt
  10. \marginparwidth = 35pt
  11. \footskip = 30pt
  • \marginparpush = 7pt (not shown)
  • \hoffset = 0pt
  • \voffset = 0pt
  • \paperwidth = 597pt
  • \paperheight = 845pt

The current details plus the layout shape can be printed from a LaTeX document itself. Use the layout package and the command of the same name: \usepackage{layout} ... \layout{}

To render a frame marking the margins of a document you are currently working on, add


to the document.

Page size[edit]

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). While this is not a serious issue (most printers will print the document without any problems), it is possible to specify alternative sizes as class option. For A4 format:


More size options with geometry[edit]

One of the most versatile packages for page layout is the geometry package. The immediate advantage of this package is that it lets you customize the page size even with classes that do not support the options. For instance, to set the page size, add the following to your preamble:


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[paperwidth=5.5in, paperheight=8.5in]{geometry}

Page size issues[edit]

If you intend to get a PDF in the end, there are basically three ways:

  • TeX → PDF
pdflatex myfile               # TeX → PDF
  • TeX → DVI → PDF
latex myfile                  # TeX → DVI
dvipdf myfile                 # DVI → PDF
  • TeX → DVI → PS → PDF
latex myfile                  # TeX → DVI
dvips myfile -o     # DVI → PS
ps2pdf myfile.pdf   # PS  → PDF

Sadly the PDF output page size may not be completely respectful of your settings. Some of these tools do not have the same interpretation of the DVI, PS and PDF specifications, and you may end up with a PDF which has not exactly the right size. Thankfully there is a solution to that: the \special command lets the user pass PostScript or PDF parameters, which can be used here to set the page size appropriately.

  • For pdflatex to work fine, using the package geometry usually works.
  • For the DVI and PS ways, the safest way to always get the right paper size in the end is to add

to the tex file, and to append the appropriate parameters to the processors used during output generation:

dvips -t a4 ...
ps2pdf -sPAPERSIZE=a4 ... # On Windows: ps2pdf -sPAPERSIZE#a4 ... [1]

If you want US Letter instead, replace 210mm,297mm by 8.5in,11in and a4paper by letter. Also replace a4 by letter in command-line parameters.

Page size for tablets[edit]

Those who want to read on tablets or other handheld digital devices need to create documents without the extra whitespace. In order to create PDF documents with optimal handheld viewing, not only must the text field and margins be adjusted, so must the page size. If you are looking for a sensible dimension, consider following the paper size used by the Supreme Court of the United States, 441pt by 666pt (or 6.125 inches by 9.25 inches), which looks great on tablets. You could also use the Supreme Court's text field size of 297 pt by 513 pt, but this is too wide for fonts other than Century Schoolbook, the font required by the Supreme Court.


Readers used to perusing typical physical literature are probably wondering why there is so much white space surrounding the text. For example, on A4 paper a document will typically have 44 mm margin widths on the left and right of the page, leaving about 60% of the page width for text. The reason is improved readability. Studies have shown[2][3] 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 optimal readability, and excessive margin white space is tolerated as a consequence. Sometimes, this white space is left in the inner margin with the assumption that the document will be bound.

If you wish to avoid excessive white space, rather than changing the margins, consider instead using a two-column (or more) layout. This approach is the one usually taken by print magazines because it provides both readable line lengths and good use of the page. Another option for reducing the amount of whitespace on the page without changing the margins is to increase the font size using the 12pt option to the document class.

If you wish to change the margins of your document, there are many ways to do so:

  • One older approach is to use the fullpage package for somewhat standardized smaller margins (around an inch), but it creates lines of more than 100 characters per line at with the 10pt default font size (and about 90 if the 12pt documentclass option is used):

For even narrower margins, the fullpage package has a cm option (around 1.5cm), which results in about 120 characters per line at the 10pt default font size, about double what is considered readable:

  • A more modern and flexible approach is to use the geometry package. This package allows you to specify the 4 margins without needing to remember the particular page dimensions commands. You can enter the measures in centimeters and inches as well. Use cm for centimeters and in for inches after each value (e.g. 1.0in or 2.54cm). Note that by default (i.e. without any options) this package already reduces the margins, so for a 'standard layout' you may not need to specify anything. These values are relative to the edge of paper (0in) and go inward. For example, this command provides more conventional margins, better using the vertical space of the page, without creating the dramatically long lines of the fullpage package (if the 11pt documentclass option is used, the line lengths are about 88 characters for letter-sized paper and slightly less when using a4paper).
\usepackage[top=1in, bottom=1.25in, left=1.25in, right=1.25in]{geometry}

It can also recreate the behavior of the fullpage package using


You can combine the margin options with the page size options seen in this paragraph.

  • You should not use the a4wide package for a page with A4 document size with smaller margins. It is obsolete and buggy. Use geometry package instead like this:
  • Edit individual page dimension variables described above, using the \addtolength and \setlength commands. See the Lengths chapter. For instance,

Odd and even margins[edit]

Using the geometry package, the options left and right are used for the inside and outside margins respectively. They also have aliases inner and outer. Thus, the easiest way to handle different margins for odd and even pages is to give the twoside option in the document class command and specify the margins as usually.

\usepackage[inner=4cm,outer=2cm]{geometry} %left=4cm,right=2cm would be equivalent

This will result in a value of 4cm on all inner margins (left margin for odd number pages and right margin for even pages) and 2cm margin on outer margins.

Setting the same value for the inner and outer for geometry will remove the difference between the margins. Another quick way to eliminate the difference in position between even and odd numbered pages would be setting the values to evensidemargin and oddsidemargin to the half of odd's default:


By default, the value of evensidemargin is larger than oddsidemargin in the two-sided layout, as one could wish to write notes on the side of the page. The side for the large margin is chosen opposite to the side where pages are joined together.

See the Lengths.

Top margin above Chapter[edit]

The top margin above a chapter can be changed using the titlesec package. Example: [11]

\titleformat{\chapter}[display]{\normalfont\huge\bfseries}{\chaptertitlename\ \thechapter}{20pt}{\Huge}

The command \titleformat must be used when the spacing of a chapter is changed. In case of a section this command can be omitted.

Page orientation[edit]

When you talk about changing page orientation, it usually means changing to landscape mode, since portrait is the default. We shall introduce two slightly different styles of changing orientation.

Change orientation of the whole document[edit]

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 we prefer is the geometry package. All you need to do is call the package, with landscape as an option:


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:


Using standard LaTeX classes, you can use the same class options:


Change orientation of specific part[edit]

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 centered on a landscaped page, one must place the tabular environment inside a table environment, which is itself inside the landscape environment. For instance it should look like this:

% ...

\centering     % optional, probably makes it look better to have it centered on the page
% ...

For books (and in general documents using the twoside option), the landscape-environment unfortunately does not pay attention to the different layout of even and odd pages. The macro can be fixed using a few lines of extra code in the preamble[4].

Change orientation of floating environment[edit]

If you use the above code, you will see that the table is inserted where it is in the code. It will not be floated! To fix this you need the package rotating. See the Rotations chapter.

Margins, page size and rotation of a specific page[edit]

If you need to rotate the page so that the figure fits, the chances are good that you need to scale the margins and the font size too. Again, the geometry package comes in handy for specifying new margins for a single page only.

% ...

\thispagestyle{empty} %% Remove header and footer.

\footnotesize %% Smaller font size.

% ...



Note that order matters!

Page styles[edit]

Page styles in Latex terms refers not to page dimensions, but to the running headers and footers of a document. These headers typically contain document titles, chapter or section numbers/names, and page numbers.

Standard page styles[edit]

The possibilities of changing the headers in plain Latex are actually quite limited. There are two commands available: \pagestyle{''style''} will apply the specified style to the current and all subsequent pages, and \thispagestyle{''style''} will only affect the current page. The possible styles are:

empty Both header and footer are cleared
plain Header is clear, but the footer contains the page number in the center.
headings Footer is blank, header displays information according to document class (e.g., section name) and page number top right.
myheadings Page number is top right, and it is possible to control the rest of the header.

The commands \markright and \markboth can be used to set the content of the headings by hand. The following commands placed at the beginning of an article document will set the header of all pages (one-sided) to contain "John Smith" top left, "On page styles" centered and the page number top right:

\markright{John Smith\hfill On page styles\hfill}

There are special commands containing details on the running page of the document.

\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"
\chaptername the name chapter in the current language. If this is English, it will display "Chapter"
\thechapter current chapter number
\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. Note that these redefinitions must be inserted after the first call of \pagestyle{fancy}. The standard book formatting of the \chaptermark is:

\renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\chaptername\ \thechapter.\ #1}}{}}

Watch out: if you provide long text in two different "parts" only in the footer or only in the header, you might see overlapping text.

Moreover, with the following commands you can define the thickness of the decorative lines on both the header and the footer:


The first line for the header, the second for the footer. Setting it to zero means that there will be no line.

Plain pages issue[edit]

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 the intended result one can follow the new section commands with \thispagestyle{empty}. The \part command, however, cannot be fixed this way, because it sets the page style, but also advances to the next page, so that \thispagestyle{} cannot be applied to that page. Two solutions:

  • simply write \usepackage{nopageno} in the preamble. This package will make \pagestyle{plain} have the same effect as \pagestyle{empty}, effectively suppressing page numbering when it is used.
  • Use fancyhdr as described below.

The tricky problem when customizing headers and footers is to get things like running section and chapter names in there. Standard 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, except if they are starred -- in such a case, \markboth{Chapter/Section name}{} must be used inside the sectioning command if header and footer lines are to be updated.

Again, several packages provide a solution:

  • an alternative one-stage mechanism is provided by the package titleps);
  • fancyhdr will handle the process its own way.

Customizing with fancyhdr[edit]

To get better control over the headers, one can use the package fancyhdr written by Piet van Oostrum. It provides several 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.

To begin, add the following lines to your preamble:


You can now observe a new style in your document.

The \headheight needs to be 13.6pt or more, otherwise you will get a warning and possibly formatting issues. Both the header and footer comprise three elements each according to its horizontal position (left, centre or right).

The styles supported by fancyhdr:

  • the four LaTeX styles;
  • fancy defines a new header for all pages but plain-style pages such as chapters and titlepage;
  • fancyplain is the same, but for absolutely all pages.

Style customization[edit]

The styles can be customized with fancyhdr specific commands. Those two styles may be configured directly, whereas for LaTeX styles you need to make a call to the \fancypagestyle command.

To set header and footer style, fancyhdr provides three interfaces. They all provide the same features, you just use them differently. Choose the one you like most.

  • You can use the following six commands.
\lhead[<even output>]{<odd output>}
\chead[<even output>]{<odd output>}
\rhead[<even output>]{<odd output>}
\lfoot[<even output>]{<odd output>}
\cfoot[<even output>]{<odd output>}
\rfoot[<even output>]{<odd output>}

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.

  • You can also use 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}

You can use multiple selectors optionally separated by a comma. The selectors are the following:

E even page
O odd page
L left side
C centered
R right side

so CE,RO will refer to the center of the even pages and to the right side of the odd pages.

  • \fancyhf is a merge of \fancyhead and \fancyfoot, hence the name. There are two additional selectors H and F to specify the header or the footer, respectively. If you omit the H and the F, it will set the fields for both.

These commands will only work for fancy and fancyplain. To customize LaTeX default style you need the \fancyplainstyle command. See below for examples.

For a clean customization, we recommend you start from scratch. To do so you should erase the current pagestyle. Providing empty values will make the field blank. So


will just delete the current heading/footer configuration, so you can make your own.

Plain pages[edit]

There are two ways to change the style of plain pages like chapters and titlepage.

First you can use the fancyplain style. If you do so, you can use the command \fancyplain{...}{...} inside fancyhdr commands like \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. For instance:

\lhead{ \fancyplain{}{Author Name} }
\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.

Alternatively 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

In that case you can use any style but fancyplain because it would override your redefinition.


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[Author Name]{}
\rhead[]{Author Name}

This is effectively saying author name is top outer, today's date is top inner, and current page number is bottom outer. Using \fancyhf can make it shorter:

\fancyhf[HLE,HRO]{Author's Name}

Here is the complete code of a possible style you could use for a two-sided document:


\renewcommand{\chaptermark}[1]{ \markboth{#1}{} }
\renewcommand{\sectionmark}[1]{ \markright{#1} }

\fancyhead[RE]{\textit{ \nouppercase{\leftmark}} }
\fancyhead[LO]{\textit{ \nouppercase{\rightmark}} }

\fancypagestyle{plain}{ %
  \fancyhf{} % remove everything
  \renewcommand{\headrulewidth}{0pt} % remove lines as well

Using \fancypagestyle one can additionally define multiple styles for one's document that are easy to switch between. Here's a somewhat complicated example for a two-sided book style:

    % Note the ## here. It's required because \fancypagestyle is making a macro (\ps@fancybook).
    % If we just wrote #1, TeX would think that it's the argument to \ps@fancybook, but
    % \ps@fancybook doesn't take any arguments, so TeX would complain with an error message.
    % You are not expected to understand this.
    \renewcommand*{\sectionmark}[1]{ \markright{\thesection\ ##1} }%
    \renewcommand*{\chaptermark}[1]{ \markboth{\chaptername\ \thechapter: ##1}{} }%
    % Increase the length of the header such that the folios 
    % (typography jargon for page numbers) move into the margin
    \fancyhfoffset[LE]{6mm}% slightly less than 0.25in
    % Put some space and a vertical bar between the folio and the rest of the header

Page n of m[edit]

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:

\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.

Alternative packages[edit]

Other packages for page styles are scrpage2, very similar to fancyhdr, and titleps, which takes a one-stage approach, without having to use \leftmark or \rightmark.

Page background[edit]

The eso-pic package will let you print content in the background of every page or individual pages.

\usepackage{tikz} % for \gradientbox below.

    \node[left color=#1,right color=#2] {#3};

          \hspace*{ \stretch{1} }\textcopyright~2013 \makeatletter\@author\makeatother.\hspace*{ \stretch{1} }

The starred-version of the \AddToShipoutPicture command applies to the current page only.

Multi-column pages[edit]

Using the twocolumn optional class argument[edit]

Using a standard Latex document class, like article, you can simply pass the optional argument twocolumn to the document class: \documentclass[twocolumn]{article} which will give the desired effect.

While this approach is useful, it has limitations. The multicol package provides the following 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.
  • multicol outputs 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.

Using multicol package[edit]

The multicol package overcomes some of the shortcomings of twocolumn and provides the multicol environment. To create a typical two-column layout:

  lots of text

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. See this section for a more detailed discussion.

The multicol package has two important parameters which can be set using \setlength:

  • \columnseprule, sets the width of the vertical rule between columns and defaults to 0pt
  • \columnsep, sets the horizontal space between columns and the defaults to 10pt, which is quite narrow

To force a break in a column, the command \columnbreak is used.

Manual page formatting[edit]

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:

\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[edit]

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:


If this does not help, you can try increasing these values even more, to a maximum of 10000. However, it is not recommended to set this value too high, as setting it to 10000 forbids LaTeX from doing this altogether, which might result in strange behavior.

It also helps to have rubber band values for the space between paragraphs:

\setlength{\parskip}{3ex plus 2ex minus 2ex}

Alternatively, you can use the needspace package to reserve some lines and thus to prevent page breaking for those lines.



A very useful troubleshooting and designing technique is to turn on the showframe option in the geometry package (which has the same effect as the showframe package described above). It draws bounding boxes around the major page elements, which can be helpful because the boundaries of various regions are usually invisible, and complicated by padding whitespace.


Notes and References[edit]

This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.

Importing Graphics[edit]

There are two possibilities to include graphics in your document. Either create them with some special code, a topic which will be discussed in the Creating Graphics part, (see Introducing Procedural Graphics) or import productions from third party tools, which is what we will be discussing here.

Strictly speaking, LaTeX cannot manage pictures directly: in order to introduce graphics within documents, LaTeX just creates a box with the same size as the image you want to include and embeds the picture, without any other processing. This means you will have to take care that the images you want to include are in the right format to be included. This is not such a hard task because LaTeX supports the most common picture formats around.

Raster graphics vs. vector graphics[edit]

Raster graphics will highly contrast with the quality of the document if they are not in a high resolution, which is the case with most graphics. The result may be even worse once printed.

Most drawing tools (e.g. for diagrams) can export in vector format. So you should always prefer PDF or EPS to PNG or JPG.

The graphicx package[edit]

As stated before, LaTeX can't manage pictures directly, so we will need some extra help: we have to load the graphicx package[12] in the preamble of our document:


This package accepts as an argument the external driver to be used to manage pictures; however, the latest version of this package takes care of everything by itself, changing the driver according to the compiler you are using, so you don't have to worry about this. Still, just in case you want to understand better how it works, here are the possible options you can pass to the package:

  • dvips (default if compiling with latex), if you are compiling with latex to get a DVI and you want to see your document with a DVI or PS viewer.
  • dvipdfm, if you are compiling with latex to get a DVI that you want to convert to PDF using dvipdfm, to see your document with any PDF viewer.
  • pdftex (default if compiling with pdflatex), if you are compiling with pdftex to get a PDF that you will see with any PDF viewer.

But, again, you don't need to pass any option to the package because the default settings are fine in most of the cases.

In many respects, importing your images into your document using LaTeX is fairly simple... once you have your images in the right format that is! Therefore, I fear for many people the biggest effort will be the process of converting their graphics files. Now we will see which formats we can include and then we will see how to do it.

Document Options[edit]

The graphics and graphicx packages recognize the draft and final options given in the \documentclass[...]{...} command at the start of the file. (See Document Classes.) Using draft as the option will suppress the inclusion of the image in the output file and will replace the contents with the name of the image file that would have been seen. Using final will result in the image being placed in the output file. The default is final.

Supported image formats[edit]

As explained before, the image formats you can use depend on the driver that graphicx is using but, since the driver is automatically chosen according to the compiler, then the allowed image formats will depend on the compiler you are using.

Consider the following situation: you have added some pictures to your document in JPG and you have successfully compiled it in PDF. Now you want to compile it in DVI, you run latex and you get a lot of errors... because you forgot to provide the EPS versions of the pictures you want to insert.

At the beginning of this book, we had stated that the same LaTeX source can be compiled in both DVI and PDF without any change. This is true, as long as you don't use particular packages, and graphicx is one of those. In any case, you can still use both compilers with documents with pictures as well, as long as you always remember to provide the pictures in two formats (EPS and one of JPG, PNG or PDF).

Compiling with latex[edit]

The only format you can include while compiling with latex is Encapsulated PostScript (EPS).

The EPS format was defined by Adobe Systems for making it easy for applications to import postscript-based graphics into documents. Because an EPS file declares the size of the image, it makes it easy for systems like LaTeX to arrange the text and the graphics in the best way. EPS is a vector format—this means that it can have very high quality if it is created properly, with programs that are able to manage vector graphics. It is also possible to store bit-map pictures within EPS, but they will need a lot of disk space.

Compiling with pdflatex[edit]

If you are compiling with pdflatex to produce a PDF, you have a wider choice. You can insert:

  • JPG, widely used on Internet, digital cameras, etc. They are the best choice if you want to insert photos.
  • PNG, a very common format (even if not as much as JPG); it's a lossless format and it's the best choice for diagrams (if you were not able to generate a vector version) and screenshots.
  • PDF, it is widely used for documents but can be used to store images as well. It supports both vector and bit-map images, but it's not recommended for the latter, as JPG or PNG will provide the same result using less disk space.
  • EPS can be used with the help of the epstopdf package. Depending on your installation,
    • you may just need to have it installed, there is no need to load it in your document;
    • if it does not work, you need to load it just after the graphicx package. Additionally, since epstopdf will need to convert the EPS file into a PDF file and store it, you need to give "writing permissions" to your compiler. This is done by adding an option to the compiling command, e.g. pdflatex -shell-escape file.tex (if you use a LaTeX editor, they usually allow to modify the command in the configuration options). Check the epstopdf documentation for other compilers.

Including graphics[edit]

Now that we have seen which formats we can include and how we could manage those formats, it's time to learn how to include them in our document. After you have loaded the graphicx package in your preamble, you can include images with \includegraphics, whose syntax is the following:

\includegraphics[attr1=val1, attr2=val2, ..., attrn=valn]{imagename}

As usual, arguments in square brackets are optional, whereas arguments in curly braces are compulsory.

The argument in the curly braces is the name of the image. Write it without the extension. This way the LaTeX compiler will look for any supported image format in that directory and will take the best one (EPS if the output is DVI; JPEG, PNG or PDF if the output is PDF). Images can be saved in multiple formats for different purposes. For example, a directory can have "diagram.pdf" for high-resolution printing, while "diagram.png" can be used for previewing on the monitor. You can specify which image file is to be used by pdflatex through the preamble command:


which specifies the files to include in the document (in order of preference), if files with the same basename exist, but with different extensions.

The variety of possible attributes that can be set is fairly large, so only the most common are covered below:

width=xx Specify the preferred width of the imported image to xx. NB. Only specifying either width or height will scale the image while maintaining the aspect ratio.
height=xx Specify the preferred height of the imported image to xx.
keepaspectratio This can be set to either true or false. When true, it will scale the image according to both height and width, but will not distort the image, so that neither width nor height are exceeded.
scale=xx Scales the image by the desired scale factor. e.g, 0.5 to reduce by half, or 2 to double.
angle=xx This option can rotate the image by xx degrees (counter-clockwise)
trim=l b r t This option will crop the imported image by l from the left, b from the bottom, r from the right, and t from the top. Where l, b, r and t are lengths.
clip For the trim option to work, you must set clip=true.
page=x If the image file is a pdf file with multiple pages, this parameter allows you to use a different page than the first.
resolution=x Specify image resolution in dpi

In order to use more than one option at a time, simply separate each with a comma. The order you give the options matters. E.g you should first rotate your graphic (with angle) and then specify its width.

Included graphics will be inserted just there, where you placed the code, and the compiler will handle them as "big boxes". As we will see in the floats section, this can disrupt the layout; you'll probably want to place graphics inside floating objects.

Also note that the trim option does not work with XeLaTex.

Be careful using any options, if you are working with the chemnum-package. The labels defined by \cmpdref{<label name>} might not behave as expected. Scaling the image for instance may be done by \scalebox instead.

The star version of the command will work for .eps files only. For a more portable solution, the standard way should take precedence. The star command will take the crop dimension as extra parameter:



OK, it's time to see graphicx in action. Here are some examples. Say you had a file 'chick.jpg' you would include it like:


This simply imports the image, without any other processing. However, it is very large (so we won't give an example of how it would look here!) So, let's scale it down:



This has now scaled it by half. If you wish to be more specific and give actual lengths of the image dimensions, this is how to go about it:


Rendering missing!

One can also specify the scale with respect to the width of a line in the local environment (\linewidth), the width of the text on a page (\textwidth) or the height of the text on a page (\textheight) (pictures not shown):


To rotate (I also scaled the image down):

\includegraphics[scale=0.5, angle=180]{chick}

Rendering missing!

And finally, an example of how to crop an image should you wish to focus on one particular area of interest:

%trim option's parameter order: left bottom right top
\includegraphics[trim = 10mm 80mm 20mm 5mm, clip, width=3cm]{chick}

Rendering missing!

Note: the presence of clip, as the trim operation will not work without it.

Trick: You can also use negative trim values to add blank space to your graphics, in cases where you need some manual alignment.

Spaces in names[edit]

If the image file were called "chick picture.png", then you need to include the full filename when importing the image:

\includegraphics[scale=0.5]{chick picture.png}


One option is to not use spaces in file names (if possible), or to simply replace spaces with underscores ("chick picture.png" to "chick_picture.png")




It is possible to have LaTeX create a border around your image by using \fbox:


You can control the border padding with the \setlength\fboxsep{0pt} command, in this case I set it to 0pt to avoid any padding, so the border will be placed tightly around the image. You can control the thickness of the border by adjusting the \setlength\fboxrule{0.5pt} command.

See Boxes for more details on \framebox and \fbox.

Graphics storage[edit]

The command \graphicspath tells LaTeX where to look for images, which can be useful if you store images centrally for use in many different documents. The \graphicspath command takes one argument, which specifies the additional paths you want to be searched when the \includegraphics command is used. Here are some examples (trailing / is required):

\graphicspath{ {/var/lib/images/} }
\graphicspath{ {images_folder/}{other_folder/}{third_folder/} }
\graphicspath{ {./images/} }
\graphicspath{ {c:\mypict~1\camera} }
\graphicspath{ {c:/mypict~1/camera/} } % works well in Win XP

Notice that, even if there is only one path given, there are two curly brackets around the path name.

Please see In the third example shown there should be a directory named "images" in the same directory as your main tex file, i.e. this is RELATIVE addressing.

Using absolute paths, \graphicspath makes your file less portable, while using relative paths (like the third example), there should not be any problem with portability. The fourth example uses the "safe" (MS-DOS) form of the Windows MyPictures folder because it's a bad idea to use directory names containing spaces. Again, ensure file names do not contain spaces or alternatively if you are using PDFLaTeX, you can use the package grffile which will allow you to use spaces in file names.

Note that you cannot make the graphicx package search directories recursively. Under Linux/Unix, you can achieve a recursive search using the environment variable TEXINPUTS, e.g., by setting it to

export TEXINPUTS=./images//:./Snapshots//

before running latex/pdflatex or your TeX-IDE. (But this, of course, is not a portable method.)

Images as figures[edit]

The figure environment is not exclusively used for images. We will only give a short preview of figures here. More information on the figure environment and how to use it can be found in Floats, Figures and Captions.

There are many scenarios where you might want to accompany an image with a caption and possibly a cross-reference. This is done using the figure environment. The following code sample shows the bare minimum required to use an image as a figure.


The above code extract is relatively trivial, and doesn't offer much functionality. The following code sample shows an extended use of the figure environment which is almost universally useful, offering a caption and label, centering the image and scaling it to 80% of the width of the text.

    \caption{Awesome Image}

Text wrapping around pictures[edit]

See Floats, Figures and Captions.

Seamless text integration[edit]

The drawback of importing graphics that were generated with a third-party tool is that font and size will not match with the rest of the document. There are still some workarounds though.

The easiest solution is to use the picture environment and then simply use the "put" command to put a graphics file inside the picture, along with any other desired LaTeX element. For example:

  width=2cm,height=2cm]{picture.eps} }

Latex picture example.png

Note that the border around the picture in the above example was added by using \fbox, so the contents of the border is the picture as generated by the above code.

Tools like Inkscape or Xfig have a dedicated LaTeX export feature that will let you use correct font and size for text in vector graphics. See #Third-party graphics tools.

For a perfect integration of graphics, you might consider procedural graphics capabilities of some LaTeX packages like TikZ or PSTricks. It lets you draw from within a document source. While the learning curve is steeper, it is worth it most of the time.

Converting graphics[edit]


You should also take a look at Export To Other Formats for other possibilities.


You can convert EPS to PDF with the epstopdf utility, included in package of the same name. This tool is actually called by pdflatex to convert EPS files to PDF in the background when the graphicx package is loaded. This process is completely invisible to the user.

You can batch convert files using the command-line. In Bourne Shell (Unix) this can be done by:

$ for i in *.eps; do epstopdf "$i"; done

In Windows, multiple files can be converted by placing the following line in a batch file (a text file with a .bat extension) in the same directory as the images:

for %%f in (*.eps) do epstopdf %%f

which can then be run from the command line.

If epstopdf produces whole page with your small graphics somewhere on it, use

$ epstopdf --gsopt=-dEPSCrop foo.eps

or try using ps2pdf utility which should be installed with Ghostscript (required for any TeX distribution).

$ ps2pdf -dEPSCrop foo.eps

to crop final PDF.


When all of the above fails, one can simplify the EPS file before attempting other conversions, by using the eps2eps tool (also see next section):

$ eps2eps input.eps input-e2.eps

This will convert all the fonts to pre-drawn images, which is sometimes desirable when submitting manuscripts for publication. However, on the downside, the fonts are NOT converted to lines, but instead to bitmaps, which reduces the quality of the fonts.


imgtops is a lightweight graphics utility for conversions between raster graphics (JPG, PNG, ...) and EPS/PS files.


Inkscape can also convert files from and to several formats, either from the GUI or from the command-line. For instance, to obtain a PDF from a SVG image you can do:

$ inkscape -z -D --file=input.svg --export-pdf=output.pdf

It is possible to run this from within a LaTeX file, the Template:LaTeX/package package (when running (pdf)latex with the --shell-escape option) can do this using Inkscape's pdf+tex export option, or a simple macro can be used. See How to include SVG diagrams in LaTeX? -- Stackexchange See Export To Other Formats for more details.


To properly edit an EPS file, you can convert it to an editable format using pstoedit. For instance, to get an Xfig-editable file, do:

$ pstoedit -f fig input.eps output.fig

And to get an SVG file (editable with any vector graphics tool like Inkscape) you can do:

$ pstoedit -f plot-svg input.eps output.svg

Sometimes pstoedit fails to create the target format (for example when the EPS file contains clipping information).


Under Windows, PDFCreator is an open source software that can create PDF as well as EPS files. It installs a virtual printer that can be accessed from other software having a "print..." entry in their menu (virtually any program).

Raster graphics converters

These three programs operate much the same way, and can convert between most graphics formats. Sam2p however is the most recent of the three and seems to offer both the best quality and to result in the smallest files.

PNG alpha channel[edit]

Acrobat Reader sometimes has problems with displaying colors correctly if you include graphics in PNG format with alpha channel. You can solve this problem by dropping the alpha channel. On Linux it can be achieved with convert from the ImageMagick program:

convert -alpha off input.png output.png

Converting a color EPS to grayscale[edit]

Sometimes color EPS figures need to be converted to black-and-white or grayscale to meet publication requirements. This can be achieved with the eps2eps of the Ghostscript package and [13] programs:

$ eps2eps input.eps input-e2.eps
$ pscol -0gray input-e2.eps input-gray.eps

Third-party graphics tools[edit]

We will not tackle the topic of procedural graphics created from within LaTeX code here (TikZ, PSTricks, MetaPost and friends). See Introducing Procedural Graphics for that.

You should prefer vector graphics over raster graphics for their quality. Raster graphics should only be used in case of photos. Diagrams of any sort should be vectors.

As we have seen before, LaTeX handles

  • EPS and PDF for vector graphics;
  • PNG and JPG for raster graphics.

If some tools cannot save in those formats, you may want to convert them before importing them.

Vector graphics[edit]


Dia is a cross platform diagramming utility which can export eps images, or generate tex drawn using the tikz package.


Another program for creating vector graphics is Inkscape. It can run natively under Windows, Linux or Mac OS X (with X11). It works with Scalable Vector Graphics (SVG) files, although it can export to many formats that can be included in LaTeX files, such as EPS and PDF. From version 0.48, there is a combined PDF/EPS/PS+LaTeX output option, similar to that offered by Xfig. There are instructions on how to save your vector images in a PDF format understood by LaTeX and have LaTeX manage the text styles and sizes in the image automatically.[1]. Today there is the svg package[2] which provides an \includesvg command to convert and include svg-graphics directly in your LaTeX document using Inkscape. You may have a look at this extended example too.

An extremely useful plug-in is textext, which can import LaTeX objects. This can be used for inserting mathematical notation or LaTeX fonts into graphics (which may then be imported into LaTeX documents).


The Ipe extensible drawing editor is a free vector graphics editor for creating figures in PDF or EPS format. Unlike Xfig, Ipe represents LaTeX fonts in their correct size on the screen which makes it easier to place text labels at the right spot. Ipe also has various snapping modes (for example, snapping to points, lines, or intersections) that can be used for geometric constructions.


Yet another solution is provided by the lpic packages [14], which allows TeX annotations to imported graphics. See Labels in the figures.

It is also possible to export vector graphics to EPS format using Draw, which is an open source office suite available for Windows, Linux and Mac.


Vector editor TpX separates geometric objects from text objects. Geometric objects are saved into .PDF file, the rest is saved in .TpX file to be processed by LaTeX. User just create the graphics in TpX editor and calls the .TpX file from latex file by command \input{...TpX}.


Xfig is a basic program that can produce vector graphics, which can be exported to LaTeX. It can be installed on Unix platforms.

On Microsoft Windows systems, Xfig can only be installed using Cygwin-X; however, this will require a fast internet connection and about 2 gigabytes of space on your computer. With Cygwin, to run Xfig, you need to first start the "Start X - Server", then launch "xterm" to bring up a terminal. In this terminal type "xfig" (without the quotation marks) and press return.

Alternatively, WinFIG is an attempt to achieve the functionality of xfig on Windows computers.

There are many ways to use xfig to create graphics for LaTeX documents. One method is to export the drawing as a LaTeX document. This method, however, suffers from various drawbacks: lines can be drawn only at angles that are multiples of 30 and 45 degrees, lines with arrows can only be drawn at angles that are multiples of 45 degrees, several curves are not supported, etc.

Exporting a file as PDF/LaTeX or PS/LaTeX, on the other hand, offers a good deal more flexibility in drawing. Here's how it's done:

  1. Create the drawing in xfig. Wherever you need LaTeX text, such as a mathematical formula, enter a LaTeX string in a textbox.
  2. Use the Edit tool to open the properties of each of those textboxes, and change the option on the "Special Flag" field to Special. This tells LaTeX to interpret these textboxes when it opens the figure.
  3. Go to File -> Export and export the file as PDF/LaTeX (both parts) or PS/LaTeX (both parts), depending on whether you are using pdflatex or pslatex to compile your file.
  4. In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image:
     \caption{Your figure}

    Observe that this is just like including a picture, except that rather than using \includegraphics, we use \input. If the export was into PS/LaTeX, the file extension to include would be .pstex_t instead of .pdf_t.

  5. Make sure to include packages graphicx and color in the file, with the \usepackage command right below the \documentclass command, like this:

And you're done!

For more details on using xfig with LaTeX, this chapter of the xfig User Manual may prove helpful.

Other tools

Commercial vector graphics software, such as Adobe Illustrator, CorelDRAW, and FreeHand are commonly used and can read and write EPS figures. However, these products are limited to Windows and Mac OS X platforms.

Raster graphics[edit]

Adobe Photoshop

It can save to EPS.


GIMP, has a graphical user interface, and it is multi-platform. It can save to EPS and PDF.

Plots and Charts[edit]

Generic Mapping Tools (GMT)

Generic Mapping Tools (GMT), maps and a wide range of highly customisable plots.


Gnumeric, spreadsheets has SVG, EPS, PDF export


Gnuplot, producing scientific graphics since 1986. If you want to make mathematical plots, then Gnuplot can save in any format. You can get best results when used along PGF/TikZ.


matplotlib, plotting library written in python, with PDF and EPS export. On the other hand there is a PGF export also. There are some tricks to be able to import formats other than EPS into your DVI document, but they're very complicated. On the other hand, converting any image to EPS is very simple, so it's not worth considering them.


R, statistical and scientific figures.

Editing EPS graphics[edit]

As described above, graphics content can be imported into LaTeX from outside programs as EPS files. But sometimes you want to edit or retouch these graphics files. An EPS file can be edited with any text editor since it is formatted as ASCII. In a text editor, you can achieve simple operations like replacing strings, changing the bounding box, or moving items slightly, but anything further becomes cumbersome. Vector graphics editors, like Inkscape, may also be able to import EPS files for subsequent editing. This approach also for easier editing. However, the importing process may occasionally modify the original EPS image.

Notes and References[edit]

Floats, Figures and Captions[edit]

The previous chapter introduced importing graphics. However, just having a picture stuck in between paragraphs does not look professional. To start with, we want a way of adding captions, and to be able to cross-reference. What we need is a way of defining figures. It would also be good if LaTeX could apply principles similar to when it arranges text to look its best to arranging pictures as well. This is where floats come into play.


Floats are containers for things in a document that cannot be broken over a page. LaTeX by default recognizes "table" and "figure" floats, but you can define new ones of your own (see Custom floats below). Floats are there to deal with the problem of the object that won't fit on the present page, and to help when you really don't want the object here just now.

Floats are not part of the normal stream of text, but separate entities, positioned in a part of the page to themselves (top, middle, bottom, left, right, or wherever the designer specifies). They always have a caption describing them and they are always numbered so they can be referred to from elsewhere in the text. LaTeX automatically floats Tables and Figures, depending on how much space is left on the page at the point that they are processed. If there is not enough room on the current page, the float is moved to the top of the next page. This can be changed by moving the Table or Figure definition to an earlier or later point in the text, or by adjusting some of the parameters which control automatic floating.

Authors sometimes have many floats occurring in rapid succession, which raises the problem of how they are supposed to fit on the page and still leave room for text. In this case, LaTeX stacks them all up and prints them together if possible, or leaves them to the end of the chapter in protest. The skill is to space them out within your text so that they intrude neither on the thread of your argument or discussion, nor on the visual balance of the typeset pages.

As with various other entities, there exist limitations on the number of floats. LaTeX by default can cope with maximum 18 floats and a symptomatic error is:

! LaTeX Error: Too many unprocessed floats.

The morefloats package lifts such limit.


To create a figure that floats, use the figure environment.

\begin{figure}[placement specifier]
... figure contents ...

The previous section mentioned how floats are used to allow LaTeX to handle figures, while maintaining the best possible presentation. However, there may be times when you disagree, and a typical example is with its positioning of figures. The placement specifier parameter exists as a compromise, and its purpose is to give the author a greater degree of control over where certain floats are placed.

Specifier Permission
h Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot)
t Position at the top of the page.
b Position at the bottom of the page.
p Put on a special page for floats only.
! Override internal parameters LaTeX uses for determining "good" float positions.
H Places the float at precisely the location in the LaTeX code. Requires the float package,[1] i.e., \usepackage{float}. This is somewhat equivalent to !ht.

What you do with these placement permissions is to list which of the options you wish to make available to LaTeX. These are simply possibilities, and LaTeX will decide when typesetting your document which of your supplied specifiers it thinks is best. Frank Mittelbach describes the algorithm[2]:

  • If a float is encountered, LaTeX attempts to place it immediately according to its rules (detailed later)
    • if this succeeds, the float is placed and that decision is never changed;
    • if this does not succeed, then LaTeX places the float into a holding queue to be reconsidered when the next page is started (but not earlier).
  • Once a page has finished, LaTeX examines this holding queue and tries to empty it as best as possible. For this it will first try to generate as many float pages as possible (in the hope of getting floats off the queue). Once this possibility is exhausted, it will next try to place the remaining floats into top and bottom areas. It looks at all the remaining floats and either places them or defers them to a later page (i.e., re-adding them to the holding queue once more).
  • After that, it starts processing document material for this page. In the process, it may encounter further floats.
  • If the end of the document has been reached or if a \clearpage is encountered, LaTeX starts a new page, relaxes all restrictive float conditions, and outputs all floats in the holding queue by placing them on float page(s).

In some special cases LaTeX won't follow these positioning parameters and additional commands will be necessary, for example, if one needs to specify an alignment other than centered for a float that sits alone in one page[3].

Use \listoffigures to add a list of the figures in the beginning of the document. To change the name used in the caption from Figure to Example, use \renewcommand{\figurename}{Example} in the figure contents.

Figures with borders[edit]

It's possible to get a thin border around all figures. You have to write the following once at the beginning of the document:


The border will not include the caption.


Floating tables are covered in a separate chapter. Let's give a quick reminder here. The tabular environment that was used to construct the tables is not a float by default. Therefore, for tables you wish to float, wrap the tabular environment within a table environment, like this:

  ... table data ...

You may feel that it is a bit long winded, but such distinctions are necessary, because you may not want all tables to be treated as a float.

Use \listoftables to add a list of the tables in the beginning of the document.

Keeping floats in their place[edit]

The placeins[15] package provides the command \FloatBarrier, which can be used to prevent floats from being moved over it. This can, e.g., be useful at the beginning of each section. The package even provides an option to change the definition of \section to automatically include a \FloatBarrier. This can be set by loading the package with the option [section] (\usepackage[section]{placeins}). \FloatBarrier may also be useful to prevent floats intruding on lists created using itemize or enumerate.

The flafter package can be used to force floats to appear after they are defined, and the endfloat[16] package can be used to place all floats at the end of a document.

The float[17] package provides the H option to floating environments, which completely stops them from floating.

Package caption[18] provides the command \captionof{<type>}{<caption text>} that lets you typeset a caption without a floating environment. You have the full and absolute control about the placement of your figures and captions.


It is always good practice to add a caption to any figure or table. Fortunately, this is very simple in LaTeX. All you need to do is use the \caption{''text''} command within the float environment. LaTeX will automatically keep track of the numbering of figures, so you do not need to include this within the caption text.

The location of the caption is traditionally underneath the float. However, it is up to you to therefore insert the caption command after the actual contents of the float (but still within the environment). If you place it before, then the caption will appear above the float. Try out the following example to demonstrate this effect:




  \caption{A picture of a gull.}

  \caption{A picture of the same gull
           looking the other way!}

    \begin{tabular}{| l c r |}
    1 & 2 & 3 \\
    4 & 5 & 6 \\
    7 & 8 & 9 \\
  \caption{A simple table}

Notice how the tables and figures
have independent counters.

Latex caption example.png

Note that the command \reflectbox{...} flips its content horizontally.

Side captions[edit]

It is sometimes desirable to have a caption appear on the side of a float, rather than above or below. The sidecap package can be used to place a caption beside a figure or table. The following example demonstrates this for a figure by using a SCfigure environment in place of the figure environment. The floatrow package is newer and has more capabilities.




  \caption{ ... caption text ... }
    {Giraffe_picture}% picture filename


Latex example sidecap.png

Unnumbered captions[edit]

In some types of document (such as presentations), it may not be desirable for figure captions to start Figure:. This is easy to suppress by just placing the caption text in the figure environment, without enclosing it in a caption. This however means that there is no caption available for inclusion in a list of figures.

Renaming table caption prefix[edit]

In case you want to rename your table caption from "Table" to something else, you can use the \captionsetup command. For example,

\captionsetup[table]{name=New Table Name}

Lists of figures and tables[edit]

Captions can be listed at the beginning of a paper or report in a "List of Tables" or a "List of Figures" section by using the \listoftables or \listoffigures commands, respectively. The caption used for each figure will appear in these lists, along with the figure numbers, and page numbers that they appear on.

The \caption command also has an optional parameter, \caption[''short'']{''long''} which is used for the List of Tables or List of Figures. Typically the short description is for the caption listing, and the long description will be placed beside the figure or table. This is particularly useful if the caption is long, and only a "one-liner" is desired in the figure/table listing. Here is an example of this usage:

\newcommand{\species}[1]{\textit{#1} sp.}


	\caption[Close up of \species{Hemidactylus}]
	{Close up of \species{Hemidactylus}, which is part the genus of the gecko family. It is the second most speciose genus in the family.}


LaTeX figure caption with lof entry.png

Labels and cross-referencing[edit]

Labels and cross-references work fairly similarly to the general case - see the Labels and Cross-referencing section for more information.

If the label picks up the section or list number instead of the figure number, put the label inside the caption to ensure correct numbering. If you get an error when the label is inside the caption, use \protect in front of the \label command.

Wrapping text around figures[edit]

An author may prefer that some floats do not break the flow of text, but instead allow text to wrap around it. (Obviously, this effect only looks decent when the figure in question is significantly narrower than the text width.)

A word of warning: Wrapping figures in LaTeX will require a lot of manual adjustment of your document. There are several packages available for the task, but none of them works perfectly. Before you make the choice of including figures with text wrapping in your document, make sure you have considered all the options. For example, you could use a layout with two columns for your documents and have no text-wrapping at all.

Anyway, we will look at the package wrapfig. Note that wrapfig may not come with the default installation of LaTeX; you might need to install additional packages. Noted also, wrapfig is incompatible with the enumerate and itemize environments

To use wrapfig, you must first add this to the preamble:


This then gives you access to:


The lineheight is expressed as the number of lines of text the figure spans. LaTeX will automatically calculate the value if this option is left blank but this can result in figures that look ugly (with too much spacing). The LaTeX calculation is manually overridden by entering the number of lines you would like the figure to span. This option can't be entered in pt, mm etc...

There are overall eight possible positioning targets:

r R right side of the text
l L left side of the text
i I inside edge–near the binding (in a twoside document)
o O outside edge–far from the binding

The uppercase-character allows the figure to float, while the lowercase version means "exactly here". [4]

The overhang of the figure can be manually set using the overhang option in pt, cm etc...

The width is, of course, the width of the figure. An example:

  \caption{A gull}
Latex example wrapfig.png

You can also allow LaTeX to assign a width to the wrap by setting the width to 0pt. \begin{wrapfigure}{l}{0pt}

Note that we have specified a size for both the wrapfigure environment and the image we have included. We did it in terms of the text width: it is always better to use relative sizes in LaTeX, let LaTeX do the work for you! The "wrap" is slightly bigger than the picture, so the compiler will not return any strange warning and you will have a small white frame between the image and the surrounding text. You can change it to get a better result, but if you don't keep the image smaller than the "wrap", you will see the image over the text.

The wrapfig package can also be used with user-defined floats with float package. See below in the section on custom floats.

Tip for figures with too much white space[edit]

You can use intextsep parameter to control additional space above and below the figure: \setlength\intextsep{0pt}

It happens that you'll generate figures with too much (or too little) white space on the top or bottom. In such a case, you can simply make use of the optional argument [lineheight]. It specifies the height of the figure in number of lines of text. Also remember that the environment center adds some extra white space at its top and bottom; consider using the command \centering instead.

Another possibility is adding space within the float using the \vspace{...} command. The argument is the size of the space you want to add, you can use any unit you want, including pt, mm, in, etc. If you provide a negative argument, it will add a negative space, thus removing some white space. Using \vspace tends to move the caption relative to the float while the [lineheight] argument does not. Here is an example using the \vspace command, the code is exactly the one of the previous case, we just added some negative vertical spaces to shrink everything up:

  \caption{A gull}

In this case it may look too shrunk, but you can manage spaces the way you like. In general, it is best not to add any space at all: let LaTeX do the formatting work!

(In this case, the problem is the use of \begin{center} to center the image. The center environment adds extra space that can be avoided if \centering is used instead.)

Alternatively you might use the picins package instead of the wrapfig package which produces a correct version without the excess white space out of the box without any hand tuning.

There is also an alternative to wrapfig: the package floatflt [19].

To remove the white space from a figure once for all, one should refer to the program pdfcrop, included in most TeX installations.


A useful extension is the subcaption[20] package, which uses subfloats within a single float. The subfigure and subfig packages are deprecated; however they are useful alternatives when used in-conjunction with LaTeX templates (i.e templates for journals from Springer and IOP, IEEETran and ACM SIG) that are not compatible with subcaption. These packages give the author the ability to have subfigures within figures, or subtables within table floats. Subfloats have their own caption, and an optional global caption. An example will best illustrate the usage of the subcaption package:


        \caption{A gull}
    ~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc. 
      %(or a blank line to force the subfigure onto a new line)
        \caption{A tiger}
    ~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc. 
    %(or a blank line to force the subfigure onto a new line)
        \caption{A mouse}
    \caption{Pictures of animals}\label{fig:animals}
Latex example subfig.png

You will notice that the figure environment is set up as usual. You may also use a table environment for subtables. For each subfloat, you need to use:

\begin{table}[<placement specifier>]
    \begin{subtable}[<placement specifier>]{<width>}
        ... table 1 ...
    \caption{<sub caption>}
    \begin{subtable}[<placement specifier>]{<width>}
        ... table 2 ...
        \caption{<sub caption>}

If you intend to cross-reference any of the subfloats, see where the label is inserted; \caption outside the subfigure-environment will provide the global caption.

subcaption will arrange the figures or tables side-by-side providing they can fit, otherwise, it will automatically shift subfloats below. This effect can be added manually, by putting the newline command (\\) before the figure you wish to move to a newline.

Horizontal spaces between figures are controlled by one of several commands, which are placed in between \begin{subfigure} and \end{subfigure}:

  • A non-breaking space (specified by ~ as in the example above) can be used to insert a space in between the subfigs.
  • Math spaces: \qquad, \quad, \;, and \,
  • Generic space: \hspace{''length''}
  • Automatically expanding/contracting space: \hfill

Wide figures in two-column documents[edit]

If you are writing a document using two columns (i.e. you started your document with something like \documentclass[twocolumn]{article}), you might have noticed that you can't use floating elements that are wider than the width of a column (using a LaTeX notation, wider than 0.5\textwidth), otherwise you will see the image overlapping with text. If you really have to use such wide elements, the only solution is to use the "starred" variants of the floating environments, that are {figure*} and {table*}. Those "starred" versions work like the standard ones, but they will be as wide as the page, so you will get no overlapping.

A bad point of those environments is that they can be placed only at the top of the page or on their own page. If you try to specify their position using modifiers like b or h, they will be ignored. Add \usepackage{dblfloatfix} to the preamble in order to alleviate this problem with regard to placing these floats at the bottom of a page, using the optional specifier [b]. Default is [tbp]. However, h still does not work.

To prevent the figures from being placed out-of-order with respect to their "non-starred" counterparts, the package fixltx2e [5] should be used (e.g. \usepackage{fixltx2e}).

Custom floats[edit]

If tables and figures are not adequate for your needs, then you always have the option to create your own! Examples of such instances could be source code examples, or maps. For a program float example, one might therefore wish to create a float named program. The package float is your friend for this task. All commands to set up the new float must be placed in the preamble, and not within the document.

  1. Add \usepackage{float} to the preamble of your document
  2. Declare your new float using: \newfloat{type}{placement}{ext}[outer counter], where:
    • type - the new name you wish to call your float, in this instance, 'program'.
    • placement - t, b, p, or h (as previously described in Placement), where letters enumerate permitted placements.
    • ext - the file name extension of an auxiliary file for the list of figures (or whatever). LaTeX writes the captions to this file.
    • outer counter - the presence of this parameter indicates that the counter associated with this new float should depend on outer counter, for example 'chapter'.
  3. The default name that appears at the start of the caption is the type. If you wish to alter this, use \floatname{type}{floatname}
  4. Changing float style can be issued with \floatstyle{style