User:Dirk Hünniger/latex
Introduction
[edit | edit source]What is TeX?
[edit | edit source]TeX is a 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, in the hope that he could reverse the trend of deteriorating typographical quality that he saw affecting his own books and articles. While TeX is a programming language in the sense that it is Turing complete, its main job is to serve as a markup language for describing how your document should look. 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 the mathematical constant , with the current version number being 3.1415926.
The name TeX is intended by its developer to be /'tɛx/, /x/ being the velar fricative, the final consonant of loch and 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.
The tools TeX offers "out of the box" are relatively primitive, and learning how to perform common tasks can require a significant time investment. Fortunately, document preparation systems based on TeX, consisting of collections of pre-built commands and macros, do exist. These systems save time by automating certain repetitive tasks; 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 | edit source]LaTeX (pronounced either "Lah-tech" or "Lay-tech") is a set of macros for TeX created by Leslie Lamport. Its purpose is to simplify the TeX typesetting, especially for documents containing mathematical formulae. Within the typesetting system, its name is formatted as LaTeX.
TeX is both a typographical and logical markup language, and one has to take account of both issues when writing a TeX document. In creating LaTeX, Lamport's aim was to split those two aspects. A typesetter can make a template and the writers can focus on LaTeX logical markup despite perhaps not knowing anything about typesetting.
In addition to the commands and options LaTeX offers, many other authors have contributed extensions, called packages or styles, which you can use for your documents. Many of these are bundled with most TeX/LaTeX software distributions; more can be found in the Comprehensive TeX Archive Network (CTAN).
Why should I use LaTeX?
[edit | edit source]Most readers will be familiar with WYSIWYG (What You See Is What You Get) typesetting systems such as LibreOffice Writer, Microsoft Word, or Google Docs. Using LaTeX is fundamentally different from using these other programs—instead of seeing your document as it comes together, you describe how you want it to look using commands in a text file, then run that file through the LaTeX program to build the result. While this has the disadvantage of needing to pause your work and take multiple steps to see what your document looks like, there are many advantages to using LaTeX:
- You can concentrate purely on the structure and contents of the document. LaTeX will automatically ensure that the typography of your document—fonts, text sizes, line heights, and other layout considerations—are consistent according to the rules you set.
- 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.
- Indexes, footnotes, citations and references are generated easily and automatically.
- Mathematical formulae can be easily typeset. (Quality mathematics was one of the original motivations of TeX.)
- Since the document source is plain text,
- Document sources can be read and understood with any text editor, unlike the complex binary and XML formats used with WYSIWYG programs.
- Tables, figures, equations, etc. can be generated programmatically with any language.
- Changes can be easily tracked with version control software.
- Some academic journals only accept or strongly recommend submissions in the form of LaTeX documents. Publishers offer LaTeX templates.
When the source file is processed by the LaTeX program, or engine, 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.
Terms regarding TeX
[edit | edit source]- Document preparation systems
LaTeX is a document preparation system based on TeX. So the system is the combination of the language and the macros.
- Distributions
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.
- Engines
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 |
---|---|
AMSTeX | A legacy TeX macro-based document preparation system used by the American Mathematical Society (AMS) from 1982 to 1985. It evolved into the AMS-LaTeX collection which includes the amsmath package used in nearly every LaTeX document as well as multiple AMS publication layout standards (document classes). |
ConTeXt | A TeX macro-based document preparation system designed by Hans Hagen and Ton Otten of Pragma ADE in the Netherlands around 1991. It is compatible with the pdfTeX, XeTeX and LuaTeX engines.
ConTeXt assumes the content author (writer of the document’s text) and the style author (designer of the document’s layout and appearance) are the same. It has a consistent and easy to understand syntax that provides the author with the tools and freedom necessary to produce a document with any desired layout. In cases where there are no standards to follow, ConTeXt provides creative freedom at the expense of required additional effort. ConTeXt excels at producing high-quality works with creative flair, such as textbooks and literature with artistically distinctive layouts. |
LaTeX | A TeX macro-based document preparation system designed by Leslie Lamport.
LaTeX assumes the content author and style author are different people. This allows authors (researchers, students, etc.) to concentrate on content and forget about design while allowing publishers (journals, graduate departments, etc.) to enforce institutional standards. Separation of content and design comes with the costs of package management, a less consistent syntax, and added complexity (compared to ConTeXt) if an author wishes to deviate from the layout designer's specification (documentclass). LaTeX excels at producing high-quality academic documents that conform to publication requirements, such as journal articles and theses. |
MetaFont | A high-quality font system designed by Donald Knuth along with TeX. |
MetaPost | A descriptive vector graphics language based on MetaFont. |
TeX | The original language designed by Donald Knuth. |
Texinfo | A TeX macro-based document preparation system designed by Richard Stallman that specializes in producing technical documentation (software manuals). |
Engines | Descriptions |
---|---|
xetex, xelatex | a TeX engine which supports Unicode input and .ttf and .otf fonts. See Fonts. |
luatex, lualatex | A TeX engine with embedded Lua support, aiming at making TeX internals more flexible. Like XeTeX, supports Unicode input and modern font files. |
pdftex, pdflatex | Generates PDF output. |
tex, latex | The "original" TeX engine. Generates DVI output. |
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's next?
[edit | edit source]In the next chapter we discuss installing LaTeX on your system. Then we will typeset our first LaTeX file.
Learning more
[edit | edit source]One of the most frustrating things beginners and even advanced users might encounter using LaTeX is the difficulty of changing the look of your documents. While WYSIWYG programs make it trivial to change fonts and layouts, LaTeX requires you to learn new commands and packages to do so. Subsequent chapters will cover many common use cases, but know that this book is only scratching the surface.
Coming from a community of typography enthusiasts, most LaTeX packages contain excellent documentation. This should be your first step if you have questions—if a package's manual has not been installed on your machine as part of your TeX distribution, it can be found on CTAN.
Other useful resources include:
- The TeX Stack Exchange Q&A
- the #latex IRC channel on Freenode
- #latexconnect
- The TeX FAQ
- The LaTeX.org forums
- Donald Knuth's original guide to TeX, The TeXbook
- Leslie Lamport's original guide to LaTeX, LaTeX: A document preparation system
Installation
[edit | edit source]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 such as Overleaf, and continue this tutorial in the next chapter. These websites offer collaborative editing 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 document preparation system along with a language. Using LaTeX requires a series 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.
Distributions
[edit | edit source]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 TeX Live, 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 which can be installed on Windows or GNU/Linux.
- 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 | edit source]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 | edit source]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 | edit source]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. Both the basic and the complete LaTeX systems are provided, with the distribution offering advanced features such as automatic installation of packages and simple interfaces to modify settings (e.g., default paper sizes).[2]
There is also a port of TeX Live available for Windows. For more, see TeX Live on Windows.
Custom installation with TeX Live
[edit | edit source]This section targets users who want fine-grained control over their TeX distribution, like an installation with a minimum of disk space usage. If not needed, the user may feel free 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 tug.org. 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 | edit source]We will give you general guidelines to install a minimal TeX distribution (i.e., only for plain TeX).
- Download the installer at http://mirror.ctan.org/systems/texlive/tlnet/install-tl-unx.tar.gz and extract it to a temporary folder.
- Open a terminal in the extracted folder and log in as root.
- 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
All administration operations for TeX Live should be made with a 022 umask. Otherwise you will not be able to use TeX at all with an unprivileged user. |
- Launch install-tl.
- Select the minimal scheme (plain only).
- 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.
- Now the options:
- use letter size instead of A4 by default: mostly for users from the USA.
- allow execution of restricted list of programs via \write18: 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.
- create all 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."
- install macro/font doc tree: useful if you are a developer, but very space consuming. Turn it off if you want to save space.
- install macro/font source tree: same as above.
- create symlinks to standard directories: symlinks are fine by default, change it if you know what you are doing.
- 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 | edit source]In a terminal write
$ tex '\empty Hello world!\bye' $ pdftex '\empty Hello world!\bye'
You should get a DVI or a PDF file accordingly.
Configuration
[edit | edit source]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. Tlmgr’s functionality completely subsumes texconfig.[1]
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 | edit source]Do not forget to set the root umask to 022 for all TeX Live administration operations. |
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. |
htlatex | Includes TeX4ht used in (LA )TeX to HTML (and XML and more) convertion. |
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>
Hyphenation
[edit | edit source]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.
Uninstallation
[edit | edit source]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.
Editors
[edit | edit source]TeX and LaTeX source documents (and its related auxiliary files) are all plain-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 (e.g., Microsoft Word, LibreOffice Writer). Dedicated LaTeX editors are more useful than generic plain text editors, because they are usually equipped with the autocomplete feature for commands, spelling and error checking and other handy macros.
Note
Microsoft Word can accept LaTeX through Equation Editor, but it is not a full-fledged LaTeX editor.
Cross-platform
[edit | edit source]Emacs
[edit | edit source]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 to use it in combination with AUCTeX and Reftex (extensions that may be installed into the Emacs program). Depending on the configuration, Emacs can provide a complete LaTeX editing environment with auto-completion, spell-checking, a complete set of keyboard shortcuts, view of table of contents, document preview and many other features.
gedit-latex-plugin
[edit | edit source]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
Gummi
[edit | edit source]Gummi is a LaTeX editor for Linux, which compiles the output of pdflatex in real-time and shows it on the right half of the screen[3].
LyX
[edit | edit source]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 — which enables users to write LaTeX documents without worrying about the actual syntax. LyX calls this a What You See Is What You Mean (WYSIWYM) approach, since the screen only shows the structure and an approximation of the output.[4]
LyX saves a document in its own markup, from which LaTeX code can then be generated. The user is mostly isolated from the LaTeX code and is not in complete control of it, and for that reason LyX is generally not considered as a proper LaTeX editor. However, since it uses LaTeX as its underlying system, knowledge of how LaTeX works can also be useful to a LyX user. In addition, if one wants to implement a feature that is not supported in the GUI, then the use of LaTeX code may be required.
TeXmaker
[edit | edit source]TeXmaker is a cross-platform editor that is very similar to Kile in both features and user interface. It is also equipped with its own PDF viewer as well.
TeXstudio
[edit | edit source]TeXstudio is a cross-platform open source LaTeX editor forked from Texmaker.
TeXworks
[edit | edit source]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 the beginners of LaTeX to write their own 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
[edit | edit source]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 | edit source]Kile
[edit | edit source]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.
GNOME-LaTeX
[edit | edit source]GNOME-LaTeX is another text editor for Linux (GNOME).
Mac OS X-only
[edit | edit source]TeXShop
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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
[edit | edit source]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.
Windows-only
[edit | edit source]LEd
[edit | edit source]TeXnicCenter
[edit | edit source]TeXnicCenter is a popular free and open source LaTeX editor for Windows. It also has a similar user interface to TeXmaker and Kile.
WinEdt
[edit | edit source]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.
WinShell
[edit | edit source]Online solutions
[edit | edit source]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 one 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 (as every article is a Git repository).
- CoCalc is a collaborative online workplace for computations, which also offers an editor for LaTeX documents.
- Overleaf is a secure, easy to use online LaTeX editor with integrated rapid preview - like Etherpad for LaTeX. One can start writing by creating a free account, and share the link or add collaborators to the projects before publishing it through their platform. It supports real time preview, Rich Text mode (a partial WYSIWYG mode with math expressions, ordered/unordered lists, sectional titles and figures in rendered form), bibliographies and custom styles. Since July 2017, ShareLaTeX is now part of Overleaf.[5][6]
- 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 | edit source]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.
Cross-platform
[edit | edit source]Mac OS X-only
[edit | edit source]- 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[7].
Viewers
[edit | edit source]Finally, you will need a viewer for the files to view LaTeX outputs. By default, LaTeX saves the final document as a .dvi (Device independent file format), but you will rarely want it to, as DVI files do not contain embedded fonts — not to mention that many document viewers are unable to open them.
In most scenarios, 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.
The following is a list of the various PDF viewers available on the web:
- PDF.js (web-library and built-in modern browsers)
- Evince (Linux GNOME)
- Foxit (Windows)
- Okular (Linux KDE)
- Preview (built-in Mac OS X)
- Reader (built-in in Windows 8 through Windows 10 1703)
- Edge PDF Viewer (built in in Windows 10)
- Adobe Acrobat Reader
- Skim (Mac OS X)
- Sumatra PDF (Windows)
- Xpdf (Linux)
- Zathura (Linux)
Tables and graphics tools
[edit | edit source]LaTeX is a document preparation system above all else: 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 (e.g., Adobe Photoshop, Canva) 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 (e.g., font, size, color). Some tools have the capability to export to LaTeX, which will partially solve this issue. See Importing Graphics for more details.
References
[edit | edit source]- ↑ a b teTeX Home Page (Retrieved August 22, 2020)
- ↑ MikTeX — All Downloads
- ↑ Gummi
- ↑ LyX
- ↑ ShareLaTeX Joins Overleaf
- ↑ The Definitive, Non-Technical Introduction to LaTeX: Overleaf
- ↑ BibDesk
Installing Extra Packages
[edit | edit source]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 | edit source]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.
Instructions for specific operating systems
[edit | edit source]On Ubuntu, with releases such as Trusty, you can use texlive and texlive-extra packages, e.g. texlive-full, texlive-latex-extra, texlive-math-extra, texlive-plain-extra, texlive-bibtex-extra, texlive-generic-extra, and language packages, which are all available here on the Ubuntu packages site, as well as here for Trusty updates. You can install these packages with sudo apt-get install <insert package name here>
.
Manual installation
[edit | edit source]Downloading packages
[edit | edit source]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ünniger/latex version 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 | edit source]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 gglo.ist -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:
- MacTeX: Users/username/Library/texmf/.
- Unix-type systems: Usually ~/texmf/. If you use TexMaker on Ubuntu 18 it may be in
/usr/share/texmf/
- MikTeX: Your local directory tree can be any folder you like, as long as you then register it as a user-managed texmf directory (see http://docs.miktex.org/manual/localadditions.html#id573803)
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.
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 |
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 http://www.tug.org/fonts/fontinstall.html#fndb):
- 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'.
This step is utterly essential, otherwise nothing will work. |
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 Map=mapfile.map (if you installed the files in a personal tree) or updmap-sys --enable Map=mapfile.map (if you installed the files in a system directory).
- MikTeX: Run initexmf --edit-config-file updmap, add the line "Map mapfile.map to the file that opens, then run initexmf --mkmaps.
See http://www.tug.org/fonts/fontinstall.html.
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 | edit source]The universal way to check if a file is available to TeX compilers is the command-line tool kpsewhich.
$ kpsewhich tikz /usr/local/texlive/2012/texmf-dist/tex/plain/pgf/frontendlayer/tikz.tex
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 | edit source]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 | edit source]The best way to look for LaTeX packages is the already mentioned CTAN: Search. Additional resources form The TeX Catalogue Online:
- Alphabetic catalogue
- With brief descriptions
- Topical catalogue with packages sorted systematically
- Hierarchical mirroring the CTAN folder hierarchy
See Also
[edit | edit source]Basics
[edit | edit source]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 | edit source]When using LaTeX, you write a plain text file which describes the document's structure and presentation. LaTeX converts this source text, combined with markup, into a typeset document. For the purpose of analogy, web pages work in a similar way: HTML is used to describe the document, which is then rendered into on-screen output - with different colours, fonts, sizes, etc. - by your browser.
You can create an input file for LaTeX with any text editor. A minimal example looks something like the following (the commands will be explained later):
\documentclass{article}
\begin{document}
Hello world!
\end{document}
|
Spaces
[edit | edit source]LaTeX normalises spaces in its input files so that whitespace characters, such as a space or a 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. More line breaks (empty lines) define 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
paragraph.
|
It does not matter whether you enter one or several spaces after a word. An empty line starts a new paragraph. |
Reserved Characters
[edit | edit source]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 square bracket characters [ ]
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, like so \\
; 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 | edit source]Sometimes a certain state should be kept local, in other words its scope should be limited.
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.
\documentclass{article}
\begin{document}
normal text {\itshape walzing \bfseries Wombat} more normal text
normal text \bgroup\itshape walzing \bfseries Wombat\egroup{} more normal text
\end{document}
|
Environments form an implicit group.
LaTeX environments
[edit | edit source]Environments in LaTeX have a role that is quite similar to commands, but they usually have effect on a wider part of the document. Their syntax is:
\begin{environmentname}
text to be influenced
\end{environmentname}
|
Between the \begin
and the \end
you can put other commands and nested environments.
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 | edit source]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.- Command names are terminated after that 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:
\commandname[option1,option2,...]{argument1}{argument2}...
|
Many LaTeX formatting commands come in pairs.
- An argument form command, where one of the arguments is the text to be formatted.
- A scope form command, where the formatting will be applied to all text after the command until the end of the current scope. That is, until the end of the current group or environment. This form may also be called a switch command. A scope form command might still have arguments, but the text to be formatted is not an argument. This form should almost never be called outside of any scope, otherwise it will apply on the rest of the document.
Confusing an argument form command with its corresponding scope form command is a very common error! |
An argument form command will have one argument more than its corresponding scope form command, the extra argument being the text the command affects.
Examples:
Emphasing text: \emph
is an argument form command with one argument, the text to be emphasised. \em
is the corresponding scope form command with no arguments.
\emph{emphasized text}, this part is normal % Correct.
{\em emphasized text}, this part is normal % Correct.
\emph emphasized text, this part is normal % Incorrect: command without argument.
\em{emphasized text}, this part is normal % Incorrect: switch with argument.
\em emphasized text, this part is normal % Dangerous: switch outside of any environment.
|
Coloring text: This example requires you to \usepackage{xcolor}
. \textcolor
is an argument form command with two arguments, the color and the text to be colored. \color
is the corresponding scope form command with only one argument, the color.
By default, this text is black. \textcolor{red}{This is red text.} Back to black.
By default, this text is black. {\color{red}This is red text.} Back to black.
|
Comments
[edit | edit source]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%
ifragilist%
icexpialidocious
|
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 | edit source]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!
\documentclass{article}
\begin{document}
Hello World!
\end{document}
|
- 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 | edit source]% 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 standard to follow, which in this case is the generic article format. Journals, university departments, etc. can provide these files to ensure publication standards are met. In many instances, the same document content can be reformatted for submission to a different publisher simply by substituting the required document class file. There are numerous generic document classes available to choose from if one is not provided. |
\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.
Building a document
[edit | edit source]We then feed our input file into a LaTeX engine, a program which generates our final document.
There are several LaTeX engines in modern use: lualatex, xelatex, and pdflatex. There are important differences between the three, but we'll discuss those elsewhere - any of them will work for building our first document.
Generating the document
[edit | edit source]LaTeX itself does not have a GUI, though some LaTeX installations feature a graphical front-end where you can click LaTeX into compiling your input file. Assuming you're not using one of those:
- Open a terminal and navigate to the directory containing your .tex file.
- Type the command:
xelatex hello.tex
(The .tex extension is not required, although you can include it if you wish.) - Various bits of info about LaTeX and its progress will be displayed. If all went well, the last two lines displayed in the console will be:
Output written on hello.pdf (1 page). Transcript written on hello.log.
This means that your source file has been processed and the resulting document is called hello.pdf. You can view it with any PDF viewer installed on your system.
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. This will be discussed in the future when it comes up.
Autobuild Systems
[edit | edit source]Compiling can be quite tricky as soon as you start working on more complex documents. A number of programs exist to automatically read in a LaTeX document and run the appropriate compilers the appropriate number of times. For example, latexmk can generate a PDF from most LaTeX files simply:
$ latexmk -pdf file.tex
Note that most editors will take care of it for you.
Historical versions of LaTeX
[edit | edit source]Both LaTeX and TeX were created many years before the Portable Document Format (PDF) existed, so the plain LaTeX engine, latex, emits DVI, a format designed by Donald Knuth for device-independent TeX output. This format has fallen out of general use, but can be converted into more common output formats using programs from your LaTeX distribution:
- dvips converts .dvi files to .ps (PostScript).
- dvipdf converts .dvi files to .pdf (dvipdfm is an improved version).
You might also find Ghostscript, a set of free and open-source tools for working with PostScript, useful. Its ps2pdf converts .ps files to .pdf, and pdf2ps does the reverse.
The following diagram shows the relationships between the LaTeX source code and the formats you can create from it:
The boxed red text represents the file formats, the blue text on the arrows represents the commands you have to use, the small dark green text under the boxes represents the image formats that are supported. Any time you pass through an arrow you lose some information, which might decrease the 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 only pdflatex for a PDF output, converting to PostScript only when it is necessary to print the document.
Note that using latex to generate DVI output keeps you from using PDF-only features, such as hyperlinks and embedded fonts.
Chapter Export To Other Formats discusses more about exporting LaTeX source to other file formats.
Files
[edit | edit source]Picking suitable filenames
[edit | edit source]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 | edit source]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.
The only important file types are .tex, .cls and .sty, .bib and .bst for BibTeX, these are not temporary and should not be deleted. |
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:
.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. |
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 | edit source]Common Elements
[edit | edit source]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 | edit source]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 | edit source]See Modular Documents for good recommendations about the way to organize big projects into multiple files.
Questions and Issues
[edit | edit source]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 | edit source]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 | edit source]See chapter Collaborative Writing of LaTeX Documents.
Document Structure
[edit | edit source]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.
Given only the logical and semantical structure of a text, LaTeX 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 | edit source]When LaTeX processes an input file, it expects it to follow a certain structure. Thus every input file must contain the commands
\documentclass{...}
\begin{document}
...
\end{document}
|
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:
\begin{document}
...
\end{document}
|
You would put your text where the dots are. The reason for marking off the beginning of your text is that LaTeX allows you to insert extra setup specifications before it (where the blank line is in the example above: we'll be using this soon). The reason for marking off the end of your text is to provide a place for LaTeX to be programmed to do extra stuff automatically at the end of the document, like making an index.
A useful side-effect of marking the end of the document text is that you can store comments or temporary text underneath the \end{document}
in the knowledge that LaTeX will never try to typeset them:
\end{document}
...
|
Preamble
[edit | edit source]Document classes
[edit | edit source]When processing an input file, LaTeX needs to know which layout standard to use. Layouts standards are contained within 'class files' which have .cls as their filename extension.
\documentclass[options]{class}
|
Here, the class
parameter for the command \documentclass
specifies the .cls file to use for the document. It is recommended to put this declaration at the very beginning. The LaTeX distribution provides additional classes for other layouts, 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
\documentclass[11pt,twoside,a4paper]{article}
|
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:
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. |
minimal | It is as small as it can get. It only sets a page size and a base font. It is mainly used for debugging purposes. |
report | For longer reports containing several chapters, small books, thesis, ... |
book | For books. |
slides | For slides. The class uses big sans serif letters. |
memoir | For sensibly changing 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). |
Here is a comprehensive list of document classes.
The generic document classes that come with LaTeX offer some layout flexibility, which is why they have a lot of options in common. Non-generic classes (those provided by university departments or publication houses) may have different options than those shown below or no options at all. Normally, third-party classes come with their own documentation. The most common options for the generic document classes are listed in the following table:
10pt, 11pt, 12pt | Sets the size of the main font in the document. If no option is specified, 10pt is assumed. |
a4paper, letterpaper,... | Defines the paper size. The default size is letterpaper; However, many European distributions of TeX now come pre-set for A4, not Letter, and this is also true of all distributions of pdfLaTeX. Besides that, a5paper, b5paper, executivepaper, and legalpaper can be specified. |
fleqn | Typesets displayed formulas left-aligned instead of centered. |
leqno | Places the numbering of 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, final | final is default. 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:
\documentclass[12pt,a4paper,oneside,draft]{report}
|
Packages
[edit | edit source]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
:
\usepackage[options]{package}
|
command, where package is the name of the package and options is a list of keywords that trigger special features in the package. For example, to use the color package, which lets you typeset in colors, you would type:
\documentclass{report}
\usepackage{color}
\begin{document}
...
\end{document}
|
You can pass several options to a package, each separated by a comma.
\usepackage[option1,option2,option3]{''package_name''}
|
The document environment
[edit | edit source]Top matter
[edit | edit source]At the beginning of most documents there will be information about the document itself, such as the title and date, and also information about the authors, such as name, address, email etc. All of this type of information within LaTeX is collectively referred to as top matter. Although never explicitly specified (there is no \topmatter
command) you are likely to encounter the term within LaTeX documentation.
A simple example:
\documentclass[11pt,a4paper]{report}
\begin{document}
\title{How to Structure a LaTeX Document}
\author{Andrew Roberts}
\date{December 2004}
\maketitle
\end{document}
|
The \title
, \author
, and \date
commands are self-explanatory. You put the title, author name, and date in curly braces after the relevant command. The title and author are usually compulsory (at least if you want LaTeX to write the title automatically); if you omit the \date
command, LaTeX uses today's date by default. You always finish the top matter with the \maketitle
command, which tells LaTeX that it's complete and it can typeset the title according to the information you have provided and the class (style) you are using. If you omit \maketitle
, the 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. You should remember, however, that the goal of LaTeX is to leave formatting to the documentclass designer, and if you wish to submit your work to multiple publishers then you should avoid designing a custom title.
Abstract
[edit | edit source]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.
\documentclass{article}
\begin{document}
\begin{abstract}
Your abstract goes here...
...
\end{abstract}
...
\end{document}
|
By default, LaTeX will use the word "Abstract" as a title for your abstract. If you want to change it into anything else, e.g. "Executive Summary", add the following line before you begin the abstract environment:
\renewcommand{\abstractname}{Executive Summary}
|
Sectioning commands
[edit | edit source]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.
\chapter{Introduction}
This chapter's content...
\section{Structure}
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 | edit source]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":
\setcounter{secnumdepth}{1}
|
A related counter is tocdepth, which specifies what depth to take the Table of Contents to. It can be reset in exactly the same way as secnumdepth. For example:
\setcounter{tocdepth}{3}
|
To get an unnumbered section heading which does not go into the Table of Contents, follow the command name with an asterisk before the opening curly brace:
\subsection*{Introduction}
|
All the divisional commands from \part*
to \subparagraph*
have this "starred" version which can be used on special occasions for an unnumbered heading when the setting of secnumdepth would normally mean it would be numbered.
If you want the unnumbered section to be in the table of contents anyway, use package unnumberedtotoc [1]. It provides the command
\addsec{Introduction}
|
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{}{}
).
\section*{Introduction}
\markright{}
\addcontentsline{toc}{section}{Introduction}
|
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:
\phantomsection
\addcontentsline{toc}{section}{Introduction}
\section*{Introduction}
|
For chapters you will also need to clear the page (this will also correct page numbering in the ToC):
\clearpage %or \cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{List of Figures}
\listoffigures
|
Section number style
[edit | edit source]See Counters.
Ordinary paragraphs
[edit | edit source]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 | edit source]All auto-numbered headings get entered in the Table of Contents (ToC) automatically. You don't have to print a ToC, but if you want to, just add the command \tableofcontents
at the point where you want it printed (usually after the Abstract or Summary).
Entries for the ToC are recorded each time you process your document, and reproduced the next time you process it, so you need to re-run LaTeX one extra time to ensure that all ToC pagenumber references are correctly calculated. We've already seen how to use the optional argument to the sectioning commands to add text to the ToC which is slightly different from the one printed in the body of the document. It is also possible to add extra lines to the ToC, to force extra or unnumbered section headings to be included.
The commands \listoffigures
and \listoftables
work in exactly the same way as \tableofcontents
to automatically list all your tables and figures. If you use them, they normally go after the \tableofcontents
command. The \tableofcontents
command normally shows only numbered section headings, and only down to the level defined by the tocdepth counter, but you can add extra entries with the \addcontentsline
command. For example if you use an unnumbered section heading command to start a preliminary piece of text like a Foreword or Preface, you can write:
\subsection*{Preface}
\addcontentsline{toc}{subsection}{Preface}
|
This will format an unnumbered ToC entry for "Preface" in the "subsection" style. You can use the same mechanism to add lines to the List of Figures or List of Tables by substituting lof or lot for toc. 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):
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{List of Figures}
\listoffigures
|
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.
Depth
[edit | edit source]The default ToC will list headings of level 3 and above. To change how deep the table of contents displays automatically the following command can be used in the preamble:
\setcounter{tocdepth}{4}
|
This will make the table of contents include everything down to paragraphs. The levels are defined above on this page. 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) :
\makeatletter
\renewcommand*{\toclevel@chapter}{-1} % Put chapter depth at the same level as \part.
\chapter{Epilogue}
\renewcommand*{\toclevel@chapter}{0} % Put chapter depth back to its default value.
\makeatother
|
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 | edit source]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]
\begin{document}
\frontmatter
\maketitle
% Introductory chapters
\chapter{Preface}
% ...
\mainmatter
\chapter{First chapter}
% ...
\appendix
\chapter{First Appendix}
\backmatter
\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:
\appendix
\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 | edit source]This is one traditional page order for books.
- Frontmatter
- Half-title
- Empty
- Title page
- Information (copyright notice, ISBN, etc.)
- Dedication if any, else empty
- Table of contents
- List of figures (can be in the backmatter too)
- Preface chapter
- Mainmatter
- Main topic
- Appendix
- Some subordinate chapters
- Backmatter
- Bibliography
- Glossary / Index
Special pages
[edit | edit source]Comprehensive papers often feature special pages at the end, like indices, glossaries and bibliographies. Since this is quite a complex topic, we will give you details in the dedicated part Special Pages.
Bibliography
[edit | edit source]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 | edit source]Text Formatting
[edit | edit source]This section will guide you through text-formatting techniques. Formatting refers to most things to do with appearance including text style and spacing. Formatting may also refer to paragraph and page layout, here we will focus on the customization of words and sentences.
Writers use formatting techniques to differentiate textual elements from the rest of the text. The many ways in which writers wish to differentiate textual elements give rise to many formatting techniques. Italicization is often used to add emphasis to key words or phrases. Footnotes are useful for providing extra information or clarification without interrupting the main flow of the text. For these reasons, formatting is very important. However, it is also very easy to abuse, and a document that has been overdone 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!
Spacing
[edit | edit source]Line Spacing
[edit | edit source]If you want to use larger inter-line spacing in a document, you can change its value by putting the
\linespread{factor}
|
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 http://tex.stackexchange.com/questions/30073/why-is-the-linespread-factor-as-it-is .
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):
\usepackage{setspace}
%\singlespacing
\onehalfspacing
%\doublespacing
%\setstretch{1.1}
|
To change line spacing within the document, the setspace package provides the environments singlespace, onehalfspace, doublespace and spacing:
This paragraph has \\ default \\ line spacing.
\begin{doublespace}
This paragraph has \\ double \\ line spacing.
\end{doublespace}
\begin{spacing}{2.5}
This paragraph has \\ huge gaps \\ between lines.
\end{spacing}
|
The line spacing value is contained in the \baselineskip length, but it is not recommended to change its value since it will have an impact on other types of content than paragraphs, which will result in an undesired effect. |
Non-breaking spaces
[edit | edit source]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. Additionally, 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.
Examples:
D.~Knuth
EUR~50
|
Sentence-spacing -- space between words and sentences
[edit | edit source]To get a straight right margin in the output, LaTeX inserts varying amounts of space between the words. By default, it follows traditional typesetting practice and inserts more space at the end of a sentence to assist the reader: an em-space rather than a word-space. This can be approximated on a typewriter or computer keyboard by pressing the space bar twice rather than once. After the invention of the typewriter, English practice was to press the spacebar twice between sentences (but not around various other punctuation), while French practice was to press the spacebar once (but then also again around various other punctuation).
The extra space added at the end of sentences is latterly considered typographically old-fashioned in current mass-market English language printing. The practice was discovered in the fifteenth century to be preferred by readers and remained the standard throughout the fifteenth to twentieth centuries. Typesetting technology changes around WWII encouraged mass-market publishers to increasingly use single spacing for cost/profit reasons, and in the late 1980s the then-innovative Macintosh DTP technology created a suddenly wide platform for the University of Chicago Press to reintroduce and evangelize William Morris's failed nineteenth century attempt to popularize the rejected early fifteenth century's close-set type as a Norm, but this time to people without industry or market knowledge. "French Spacing" was redefined at this time in the USA (only) as a pejorative term to describe its opposite: to mean em-spacing between sentences rather than word-spacing. LaTeX users should note that Donald Knuth created TeX specifically to correct what he described as the ugliness and unreadability of then-(70s, pre-MacintoshDTP)-machine-typesetting, that he later added the FrenchSpacing option not as default but as a lengthily-specified option, i.e. that original TeX assumed the user wanted reader-centric typesetting (em-spacing sentences not word-spacing), and that Donald Knuth explicitly coded the FrenchSpacing option to implement precisely the opposite of what current post-University-of-Chicago typographers declare it to mean despite him being "otherwise" regarded as extremely intelligent and extremely well informed.) 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
\frenchspacing
|
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 before a space generates a space that will not be enlarged. A tilde ‘~
’ character generates a non-breaking space. The command \@
before 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 | edit source]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.
\maketitle
\vfill
\tableofcontents
\clearpage
\section{My first section}
% ...
|
See Lengths for more details.
Manual spacing
[edit | edit source]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.
Hyphenation
[edit | edit source]LaTeX hyphenates words whenever necessary. Hyphenation rules will vary for different languages. LaTeX supports only 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 (separated by blanks) 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: https://www.tug.org/TUGboat/tb33-1/tb103hyf.pdf).
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}
|
With babel, the recommended command to set hyphenation exceptions is \babelhyphenation
. When LuaTeX is used, babel also allows to add new patterns and modify existing ones (with \babelpatterns
), as well as to define non-standard rules (like ‘ff’ to ‘ff-f’ in some languages, or ranked hyphenation) to be applied without explicit mark-up (with \babelposthyphenation
).
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.
\begin{minipage}{2in}
I think this is: su\-per\-cal\-%
i\-frag\-i\-lis\-tic\-ex\-pi\-%
al\-i\-do\-cious
\end{minipage}
|
|
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:
\usepackage{hyphenat}
|
one should write, instead of electromagnetic-endioscopy:
electromagnetic\hyp{}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:
\usepackage[shortcuts]{extdash}
|
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:
electromagnetic\-/endioscopy
L\=/approximation
|
One or more words can be kept together on the one line with the standard LaTeX command:
\mbox{text}
|
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:
\hyphenpenalty=100000
|
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
\usepackage{geometry}
|
will widen the text width and reduce the amount of margin overruns.
Quote-marks
[edit | edit source]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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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:
\usepackage[T1]{fontenc}
|
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 | edit source]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
[edit | edit source]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
a very long word ABCDEFGHIJKLMNOPRST;
then we have another bad thing
--- a long number 1234567890123456789.
\begin{sloppypar}
This is a paragraph with
a very long word ABCDEFGHIJKLMNOPRST;
then we have another bad thing
--- a long number 1234567890123456789.
\end{sloppypar}
|
Another solution is to edit the text to avoid long words, numbers or URLs approaching the side margin.
Ligatures
[edit | edit source]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. A classic example is shelfful:[2]
\Large Not shelfful\\
but shelf{}ful
|
If you are using LuaLaTeX, you can automate some of this work with the selnolig package.
Slash marks
[edit | edit source]When the slash character /
is immediately preceded and/or followed by text without intervening white space, LaTeX does not allow a line break to occur between the slash and adjacent text. This behaviour was implemented because historically most occurrences of the slash within text were situations where the convention was to keep the surrounding text together on one line. Examples include
- Dates, such as "
1/1/2021
". - Abbreviations of units, such as "
mm/year
".
Dates and unit abbreviations are relatively short, so the constraint that they must be kept together on a single line does not cause issues. However, the /
character can also occur in longer expressions which might create "overfull" errors in output, causing text to overflow a margin. In these situations the /
character should be replaced by "\slash
", which allows the line to "break" after the slash mark if needed. Examples include
- Words separated by slashes, such as "input/output" which should be typeset as "
input\slash output
", or Yes/No/Cancel. (Shorter examples like and/or could be safely left as not allowing a line break.) - Directory names in operating systems that use the slash as a separator, such as /home/texlion/Documents, which should be typeset as "
/home\slash texlion\slash Documents
". Note that the first of the 3 slashes is NOT replaced.
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
input\slash\hspace{0pt}output
|
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.
Fonts
[edit | edit source]To change the font family, emphasize text, and other font-related issues, see Fonts.
Formatting macros
[edit | edit source]Even if you can easily change the output of your fonts using those commands, you're better off not using explicit commands like this, because they work in opposition to the basic idea of LaTeX, which is to separate the logical and visual markup of your document. This means that if you use the same font changing command in several places in order to typeset a special kind of information, you should use \newcommand
to define a "logical wrapper command" for the font changing command.
\newcommand{\oops}[1]{\textit{#1}}
Do not \oops{enter} this room,
it’s occupied by \oops{machines}
of unknown origin and purpose.
|
Do not enter this room, it’s occupied by machines of unknown origin and purpose. |
This approach has the advantage that you can decide at some later stage that you want to use some visual representation of danger other than \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 | edit source]Sub and superscripting can be done quite easily using \textsubscript{}
and \textsuperscript{}
.
\documentclass{article}
\begin{document}
Wombat\textsubscript{walzing}
Michelangelo was born on March 6\textsuperscript{th}, 1475.
\end{document}
|
Note: A LaTeX version from 2015 or later, or the package fixltx2e, is needed to use text-mode subscripts in all contexts.[3]
Text figures ("old style" numerals)
[edit | edit source]Text figures can also be enabled and disabled with fontspec when using OpenType fonts that support them. See Fonts. |
Many typographers prefer to use titling figures, sometimes called lining figures, when numerals are interspersed with full caps, when they appear in tables, and when they appear in equations, using text figures elsewhere. LaTeX allows this usage through the \oldstylenums{}
command:
\oldstylenums{1234567890}
|
Some fonts do not have text figures built in; the textcomp package attempts to remedy this by effectively generating text figures from the currently-selected font. Put \usepackage{textcomp}
in your preamble. textcomp also allows you to use decimal points, properly formatted dollar signs, etc. within \oldstylenums{}
.
One common use for text figures is in section, paragraph, and page numbers. These can be set to use text figures by placing some code in your preamble:
\usepackage{textcomp}
% Enclose everything in an \AtBeginDocument{}
\AtBeginDocument{%
% Make \section{} use text figures
\let\myTheSection\thesection
\renewcommand{\thesection}{ \oldstylenums{\myTheSection} }
% Make \paragraph{} use text figures
\let\myTheParagraph\theparagraph
\renewcommand{\theparagraph}{ \oldstylenums{\myTheParagraph} }
% Make the page numbers in text figures
\let\myThePage\thepage
\renewcommand{\thepage}{ \oldstylenums{\myThePage} }
}
|
Should you use additional sectioning or paragraphing commands, you may adapt the previous code listing to include them as well.
- Note
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:
...
\tableofcontents
\pagenumbering{roman}
\chapter{Preface}
...
\chapter{Introduction}
...
\pagenumbering{arabic}
% without this, the \thepage command will not be in oldstyle (e.g., in your Table of Contents}
\renewcommand{\thepage}{ \oldstylenums{\myThePage} }
\Chapter{Foo}
...
|
Dashes and hyphens
[edit | edit source]LaTeX knows four kinds of dashes: a hyphen (-), en dash (–), em dash (—), or a minus sign (−). You can access three of them with different numbers of consecutive dashes. The fourth sign is actually not a dash at all—it is the mathematical minus sign:
Hyphen: daughter-in-law, X-rated\\
En dash: pages 13--67\\
Em dash: yes---or no? \\
Minus sign: $0$, $1$ and $-1$
|
The names for these dashes are: ‘-’(-) hyphen , ‘--’(–) en-dash , ‘---’(—) em-dash and ‘’(−) minus sign. They have different purposes:
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 | edit source]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
|
Alternatively, you can use the \textellipsis
command which allows the spacing between the dots to vary.
Ready-made strings
[edit | edit source]There are some very simple LaTeX commands for typesetting special text strings:
Notes and References
[edit | edit source]- ↑ hyphenat package documentation, p3
- ↑ Knuth, Donald. "Chapter 5: Grouping". The TeXbook. p. 19.
- ↑ http://tex.stackexchange.com/questions/1013/how-to-typeset-subscript-in-usual-text-mode
This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.
Paragraph Formatting
[edit | edit source]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 | edit source]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.
There is no way (in standard LaTeX) to set full justification explicitly. It means that if you do not enclose the previous 3 commands into a group, the rest of the document will be affected.
So the right way of doing this with commands is
|
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
[edit | edit source]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 plus 4mm minus 3mm}
|
If you want to indent a paragraph that is not indented, you can use
\indent
|
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
\noindent
|
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
\usepackage{parskip}
\setlength{\parindent}{15pt}
|
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 | edit source]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} \\
Text...
|
Alternatively, you can use the shorter, yet not completely equivalent syntax:
\paragraph{Title} ~\\
Text...
|
You can also change ${}$
(an empty inline mathematical expression) for \hspace{0pt}
or ~
in the above makeshift.
Line spacing
[edit | edit source]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 | edit source]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. |
\\[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. |
\\*
|
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. |
\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 (allow but not encourage a line break) 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)
|
If used in horizontal mode, this is equivalent to `\linebreak`, if used in vertical mode it is equivalent to `\pagebreak`. |
\par (TeX)
|
Ends the current paragraph. It is equivalent to leaving a blank line in the input. |
- If you use these comments to put a break in a section heading, the line will also be broken in the table of contents. To avoid such a division, you can use the
\section[]{}
command, which is described in sectioning commands.
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 | edit source]Verbatim text
[edit | edit source]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:
\begin{verbatim}
The verbatim environment
simply reproduces every
character you input,
including all s p a c e s!
\end{verbatim}
|
Note: once in the verbatim environment, the only command that will be recognized is \end{verbatim}
. Any others will be output. 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:
\begin{alltt}
Verbatim extended with the ability
to use normal commands. Therefore, it
is possible to \emph{emphasize} words in
this environment, for example.
\end{alltt}
|
Remember to add \usepackage{alltt}
to your preamble to use it though!
Within the alltt environment, you can use the command \normalfont
to get back the normal font.
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 | edit source]One of either the hyperref or url packages provides the \url
command, which properly typesets URLs, for example:
Go to \url{http://www.uni.edu/~myname/best-website-ever.html} for my website.
|
will show this URL exactly as typed (similar to the \verb
command), but the \url
command also performs a hyphenless break at punctuation characters (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:
\urlstyle{same}
|
See also Hyperlinks
Listing environment
[edit | edit source]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 alongside the text. The command is \begin{listing}[step]{first line}
. The mandatory first line argument is for specifying which line the numbering should start at. 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 | edit source]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:
\usepackage{verbatim}
|
(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
\begin{comment}
rather stupid,
but helpful
\end{comment}
example for embedding
comments in your document.
|
This is another example for embedding comments in your document. |
Note that this won’t work inside complex environments, like math for example. You may be wondering, why should I load a package called verbatim to have the possibility to add comments? The answer is straightforward: commented text is interpreted by the compiler just like verbatim text, the only difference is that verbatim text is introduced within the document, while the comment is just dropped.
Alternatively, you can define a \comment{}
command, by adding the following to the document's preamble:
\newcommand{\comment}[1]{}
|
Then, to comment out text, simply do something like this:
\comment{This is a long comment and can extend over multiple lines, etc.} 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
\newcommand{\comment}[2]{#2}
|
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 | edit source]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
$$\int_{-\infty}^\infty\mathrm{d}x\,x^{-2}$$
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 | edit source]LaTeX provides several environments for quoting text; they have small differences and they are aimed for different types of quotations. All of them are indented on either margin, and you will need to add your own quotation marks if you want them. The provided environments are:
- quote
- for a short quotation, or a series of small quotes, separated by blank lines.
- quotation
- for use with longer quotations, of more than one paragraph, because it indents the first line of each paragraph.
- verse
- is for quotations where line breaks are important, such as poetry. Once in, new stanzas are created with a blank line, and new lines within a stanza are indicated using the newline command,
\\
. If a line takes up more than one line on the page, then all subsequent lines are indented until explicitly separated with\\
.
Abstracts
[edit | edit source]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 | edit source]This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.
Colors
[edit | edit source]Adding colors to your text is supported by the xcolor package (supersedes package color). 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 xcolor package
[edit | edit source]To make use of these features, the xcolor package must be imported. xcolor starts from the basic facilities of the color package and extends it.
\usepackage{xcolor}
|
The package allows you to use the names of 19 base colors (black, white, blue, green, yellow, red etc.); these names are always available. Besides, the package has some options to get more predefined colors, which should be added globally. dvipsnames allows you to access more than 60 colors, and svgnames allows access to about 150 colors. If you need more color names, then you may also want to look at the x11names option that offers more than 300 colors.
The table option allows colors to be added to tables.
Entering colored text
[edit | edit source]The simplest way to type colored text is by:
\textcolor{declared-color}{text}
|
where declared-color is a color that, if necessary, was previously defined 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.
|
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:
\pagecolor{declared-color}
|
Entering colored background for the text
[edit | edit source]
\colorbox{declared-color}{text}
|
If the background color and the text color is changed, then:
\colorbox{declared-color1}{\color{declared-color2}text}
|
There is also \fcolorbox to make framed background color in yet another color:
\fcolorbox{declared-color-frame}{declared-color-background}{text}
|
Predefined colors
[edit | edit source]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 | edit source]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.
\usepackage[dvipsnames]{xcolor}
|
This above syntax may result in an error if you are using beamer with tikz. To go around it, include usenames and dvipsnames options when defining the document class.
\documentclass[usenames,dvipsnames]{beamer}
|
Be wary that the below color names are case-sensitive. For example, \color{olivegreen}
raises an "undefined color" error, but \color{OliveGreen}
works fine. Table can be sorted by color name, by hue, by saturation, or by lightness.
Name | Color | Hex | Hue | Saturation | Lightness |
---|---|---|---|---|---|
Apricot | FBB982 | 27.3 | 239.2 | 190.5 | |
Aquamarine | 00B5BE | 182.8 | 255.0 | 95.0 | |
Bittersweet | C04F17 | 19.9 | 200.4 | 107.5 | |
Black | 221E1F | 0.3 | 15.9 | 32.0 | |
Blue | 2D2F92 | 238.2 | 134.8 | 95.5 | |
BlueGreen | 00B3B8 | 181.6 | 255.0 | 92.0 | |
BlueViolet | 473992 | 249.4 | 111.8 | 101.5 | |
BrickRed | B6321C | 8.6 | 187.0 | 105.0 | |
Brown | 792500 | 18.3 | 255.0 | 60.5 | |
BurntOrange | F7921D | 32.2 | 237.6 | 138.0 | |
CadetBlue | 74729A | 243.0 | 42.1 | 134.0 | |
CarnationPink | F282B4 | 333.2 | 207.0 | 186.0 | |
Cerulean | 00A2E3 | 197.2 | 255.0 | 113.5 | |
CornflowerBlue | 41B0E4 | 199.1 | 191.5 | 146.5 | |
Cyan | 00AEEF | 196.3 | 255.0 | 119.5 | |
Dandelion | FDBC42 | 39.1 | 249.7 | 159.5 | |
DarkOrchid | A4538A | 319.3 | 83.6 | 123.5 | |
Emerald | 00A99D | 175.7 | 255.0 | 84.5 | |
ForestGreen | 009B55 | 152.9 | 255.0 | 77.5 | |
Fuchsia | 8C368C | 300.0 | 113.0 | 97.0 | |
Goldenrod | FFDF42 | 49.8 | 255.0 | 160.5 | |
Gray | 949698 | 0.2 | 4.9 | 150.0 | |
Green | 00A64F | 148.6 | 255.0 | 83.0 | |
GreenYellow | DFE674 | 63.7 | 177.3 | 173.0 | |
JungleGreen | 00A99A | 174.7 | 255.0 | 84.5 | |
Lavender | F49EC4 | 333.5 | 203.1 | 201.0 | |
LimeGreen | 8DC73E | 85.4 | 140.3 | 130.5 | |
Magenta | EC008C | 324.4 | 255.0 | 118.0 | |
Mahogany | A9341F | 9.1 | 176.0 | 100.0 | |
Maroon | AF3235 | 358.6 | 141.7 | 112.5 | |
Melon | F89E7B | 16.8 | 229.3 | 185.5 | |
MidnightBlue | 006795 | 198.5 | 255.0 | 74.5 | |
Mulberry | A93C93 | 312.1 | 121.4 | 114.5 | |
NavyBlue | 006EB8 | 204.1 | 255.0 | 92.0 | |
OliveGreen | 3C8031 | 111.6 | 113.8 | 88.5 | |
Orange | F58137 | 23.4 | 230.7 | 150.0 | |
OrangeRed | ED135A | 340.5 | 218.9 | 128.0 | |
Orchid | AF72B0 | 299.0 | 71.9 | 145.0 | |
Peach | F7965A | 22.9 | 231.4 | 168.5 | |
Periwinkle | 7977B8 | 241.8 | 80.1 | 151.5 | |
PineGreen | 008B72 | 169.2 | 255.0 | 69.5 | |
Plum | 92268F | 301.7 | 149.7 | 92.0 | |
ProcessBlue | 00B0F0 | 196.0 | 255.0 | 120 | |
Purple | 99479B | 298.6 | 94.8 | 113.0 | |
RawSienna | 974006 | 24.0 | 235.5 | 78.5 | |
Red | ED1B23 | 357.7 | 217.7 | 132.0 | |
RedOrange | F26035 | 13.7 | 224.2 | 147.5 | |
RedViolet | A1246B | 325.9 | 161.8 | 98.5 | |
Rhodamine | EF559F | 331.2 | 211.1 | 162.0 | |
RoyalBlue | 0071BC | 203.9 | 255.0 | 94.0 | |
RoyalPurple | 613F99 | 262.7 | 106.3 | 108.0 | |
RubineRed | ED017D | 328.5 | 252.9 | 119.0 | |
Salmon | F69289 | 5.0 | 218.9 | 191.5 | |
SeaGreen | 3FBC9D | 165.1 | 127.0 | 125.5 | |
Sepia | 671800 | 14.0 | 255.0 | 51.5 | |
SkyBlue | 46C5DD | 189.5 | 175.8 | 145.5 | |
SpringGreen | C6DC67 | 71.3 | 159.5 | 161.5 | |
Tan | DA9D76 | 23.4 | 146.6 | 168.0 | |
TealBlue | 00AEB3 | 181.7 | 255.0 | 89.5 | |
Thistle | D883B7 | 323.3 | 133.0 | 173.5 | |
Turquoise | 00B4CE | 187.6 | 255.0 | 103.0 | |
Violet | 58429B | 254.8 | 102.7 | 110.5 | |
VioletRed | EF58A0 | 331.4 | 210.4 | 163.5 | |
White | FFFFFF | 0.1 | 0.0 | 255.0 | |
WildStrawberry | EE2967 | 341.1 | 217.5 | 139.5 | |
Yellow | FFF200 | 56.9 | 255.0 | 127.5 | |
YellowGreen | 98CC70 | 93.9 | 120.9 | 158.0 | |
YellowOrange | FAA21A | 36.4 | 244.1 | 138.0 |
Defining new colors
[edit | edit source]If the predefined colors are not adequate, you may wish to define your own.
Place
[edit | edit source]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.)
Method
[edit | edit source]You need to include the xcolor package in your preamble to define new colors. In the abstract, the colors are defined following this scheme:
\definecolor{name}{model}{color-spec}
|
where:
- 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 | edit source]Among the models you can use to describe the color are the following (several more are described in the xcolor manual):
Model | Description | Color Specification | Example |
---|---|---|---|
gray | Shades of gray (0-1) |
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 (0-1) |
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 (0-255) |
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 (00-FF) |
Six hexadecimal numbers given in the form RRGGBB; similar to what is used in HTML. | \definecolor{orange}{HTML}{FF7F00} |
cmyk | Cyan, Magenta, Yellow, Black (0-1) |
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} |
Examples
[edit | edit source]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:
\definecolor{orange}{rgb}{1,0.5,0}
|
The following code should give a similar results to the last code chunk.
\definecolor{orange}{RGB}{255,127,0}
|
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.
\color{blue!20}
\color{blue!20!black}
\color{blue!20!black!30!green}
|
xcolor also features a handy command to define colors from color mixes:
\colorlet{notgreen}{blue!50!yellow}
|
Using color specifications directly
[edit | edit source]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 | edit source]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:
- Linux/BSD: The gcolor2 tool (usually also available in repositories)
- Linux/BSD: in newer systems you may want to use gcolor3 tool (usually also available in repositories)
- Microsoft Windows: The open-source Color Selector tool.
- Apple Macs: Hex Color Picker for creating custom colors and the built-in DigitalColor Meter for capturing colors on screen.
- Online utilities: See here for a Wikipedia article with several external links
Spot colors
[edit | edit source]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 (CMYK and CIELAB). They are defined with, say:
\definespotcolor{mygreen}{PANTONE 7716 C}{.83, 0, .40, .11}
|
Sources
[edit | edit source]
Fonts
[edit | edit source]Font families
[edit | edit source]There are hundreds—if not thousands—of typefaces, or font families. Common examples include Times, Courier, and Helvetica. These families can generally be grouped into three main categories: serif, sans serif, and monospaced. LaTeX commands generally refer to these with the shorthand rm, sf, and tt respectively.
By default, LaTeX uses Computer Modern, a family of typefaces designed by Donald Knuth for use with TeX. It contains serif, sans serif, and monospaced fonts, each available in several weights and optical sizes.
The bodies of LaTeX documents are set in Roman (serif) type by default, but this can be changed by setting the family default:
\renewcommand{\familydefault}{<family>}
|
where <family> is any of the following:
\rmdefault
\sfdefault
\ttdefault
Emphasizing text
[edit | edit source]Tex recognizes two types of markup commands:
- Semantic -
\emph{text}
-- by default italise font. Can be overwritten by\renewcommand\emph{\textbf}
. Replace textbf per requirements/preferences. - Visual - which actually applies required formatting:
- Family -
\textrm{}
\textsf{}
\texttt
- Weight -
\textbf{}
- bold,\textmd{}
- medium - Shape -
\textup{}
,\textit{}
,\textsl{}
- Family -
There are variation of the visual markup for a specific font. The above are commonly used elements. For reference on the items see section Font styles
To add some emphasis to a word or a phrase, use the \emph{text}
command, which usually italicizes the text.
I want to \emph{emphasize} a word.
|
I want to emphasize a word. |
The 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. |
Do not overuse emphasis in your paragraphs. Emphasis should be reserved for key terms or other particularly important concepts in a text, and bold text especially used minimally.[1] |
Font styles
[edit | edit source]Typefaces usually come in various styles and weights, such as italic and bold. The following table lists the commands you will need to access typical font shapes.
Note: Paragraph breaks are not allowed inside the command forms.
LaTeX command | Equivalent switch | 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. Depending on the font zero have a dash in it to differenciate from letter O |
\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 | The normal font weight. |
\textlf{...}
|
{\lfseries ...}
|
light | A font weight lighter than normal. Not supported by all typefaces. |
Generally, one should prefer the commands over their equivalent switches because the former automatically corrects spacing immediately following the end of the selected style.
You may have noticed the absence of underline—this is because underlining is a byproduct of the typewriter era, and is not recommended when bold and italic type is available instead.[2]
However, underlining can be useful in some cases, such as to draw attention to changes during editing. Although underlining is available via the \underline{...}
command, text underlined in this way will not break properly. Instead, use the \ul{...}
command from the soul package or \uline{...}
command from the ulem (underline emphasis) package. By default, the latter package also overrides \emph
to underline instead of italicize the text. In the likely case that this is not your intent, use the normalem
option, i.e. \usepackage[normalem]{ulem}
. Both packages also provide strikethrough text with \st{...}
or \sout{...}
, respectively.
Sizing text
[edit | edit source]Built-in sizes
[edit | edit source]To scale text relative to the default body text size, use the following commands:
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. 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.
{\Large\tableofcontents}
|
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.
By default, \normalsize
is 10 points, but this can be changed in the \documentclass
declaration,
e.g. \documentclass[12pt]{article}
.
Note that not every document class has unique sizes for all of the above size commands.
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 |
Points in TeX follow the standard American point system 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)).
Arbitrary sizes
[edit | edit source]The \tiny
...\Huge
commands are often enough for your needs, but you may occasionally want an arbitrary font size. This is done with \fontsize{<size>}{<line space>}\selectfont
. For example:
\fontsize{5cm}{5.5cm}\selectfont
|
sets the current font size to 5cm with 5.5 centimeter leading.
If you are using the latex or pdflatex engines, you may get a warning similar to the following:
LaTeX Font Warning: Font shape `OT1/cmr/m/n' in size <142.26378> not available (Font) size <24.88> substituted on input line 103.
This is because these older engines only support a fixed set of sizes—between 5 and 17 point. When he designed Computer Modern, Knuth created individual font files for these sizes, each with stroke widths and spacing optimized for that particular size. To avoid distorting them, scaling these fonts is disabled by default.
This issue is avoided when using lualatex or xelatex, which use Latin Modern - a vectorized version of Computer Modern - as the default font family. This still provides individual files at each of the original optical sizes, but will automatically scale the closest one when asked for an arbitrary size.
Using alternative fonts
[edit | edit source]When TeX was originally designed in the late 1970s, vector-based fonts didn't exist in any common format - PostScript wouldn't be released until 1982. Consequently, TeX was designed to use its own font system, METAFONT. Over time, TeX (and LaTeX) were extended to support PostScript fonts, and modern LaTeX engines also support the TrueType (TTF) and OpenType (OTF) fonts found on modern systems.
Using TTF and OTF fonts
[edit | edit source]If you are using lualatex or xelatex, you can use TTF and OTF fonts with the fontspec package:
\documentclass{article}
\usepackage{fontspec}
\setmainfont[Ligatures=TeX]{Georgia}
\setsansfont[Ligatures=TeX]{Arial}
\begin{document}
Lorem ipsum...
\end{document}
|
The [Ligatures=TeX]
option allows you to use the standard TeX ligatures mentioned in the Text Formatting chapter instead of Unicode characters that are unlikely to be on your keyboard. For example, --- can be used to create em dashes (—), quotes can be typed ``like this''
instead of “like this”
, and so on.
The fontspec package is extremely configurable. See the manual[3] for details, but some basics are covered below.
Selecting font files
[edit | edit source]Different weights and styles of a given typeface are usually stored as separate font files. A typical typeface might offer four files to represent its normal weight, italics, bold, and bold italics. Given a typefaces's name, fontspec can generally deduce the names of the individual files. However, many typefaces come in more than two weights—some versions of Futura, for example, comes in light, book, medium, demi, bold, and extra bold weights. Sometimes small caps are stored as separate files as well.
We might want to hand-pick weights to achieve a certain look or better match the weights of other fonts in our document. Continuing to use Futura as an example, say we want to use the "book" weight for our default weight, "demi" for bold, and the font files are named:
- Futura-Boo for upright book weight
- Futura-BooObl for oblique book weight
- FuturaSC-Boo for small caps, book weight
- Futura-Dem for upright demi(bold)
- Futura-DemObl for oblique demibold
Our font setup might resemble:
\usepackage{fontspec}
\setmainfont[
Ligatures=TeX,
UprightFont = *-Boo,
ItalicFont = *-BooObl,
SmallCapsFont = *SC-Boo,
BoldFont = *-Dem,
BoldItalicFont = *-DemObl
]{Futura}
|
Note that instead of typing out Futura-Boo, Futura-BooObl, and so on, we can use * to insert the base name.
Controlling font features
[edit | edit source]The OpenType (OTF) format allows type designers to embed font features that can be turned on and off, such as:
- Alternate versions of glyphs
- Lining and "oldstyle" figures, each with tabular and proportional spacing[4]
- Up to three sets of ligatures: standard, contextual, and historical
- Superscript and subscript glyphs
- Small caps (in the same file as the standard upper and lowercase characters)
All of these features can be turned on and off using different fontspec options. If we wanted to set our body text in Linux Libertine with oldstyle, proportionally-spaced figures, for example, we might set up our fonts as follows:
\setmainfont[
Ligatures=TeX,
Numbers={OldStyle, Proportional}
]{Linux Libertine}
|
Features can be turned on and off using \addfontfeatures{...}
. Say you wanted to set a table in lining, tabular figures:
{\addfontfeatures{Numbers={Lining, Tabular}}
\begin{tabular}{l r}
Widgets: & 25 \\
Gadgets: & 6 \\
Whatsits & 24 \\
\end{tabular}
} % Return to previous figure style
|
Changing fonts in latex and pdflatex
[edit | edit source]If you are not using one of the Unicode-aware engines, font selection is more complicated. (See the discussion of encoding below.) Useful resources for latex and pdflatex font configuration include:
- The Latex Font Catalogue
- LaTeX font commands
- How to change fonts in Latex
- Understanding the world of TEX fonts and mastering the basics of fontinst
- Font installation the shallow way "For one-off projects, you can cut corners with font installation (i.e. fontinst) and end up with a more manageable set of files and a cleaner TEX installation. This article shows how and why"
Font encoding
[edit | edit source]Digitising human language is a complicated topic that has evolved significantly since TeX's inception.
Unicode
[edit | edit source]Today, text is usually represented in computer systems using Unicode. Briefly,
- A Unicode text file is made of a series of code points, each of which can represent a character to be drawn, an accent or other diacritical mark to combine with an adjacent character, or some non-printing character, such as instruction to print subsequent text right-to-left.
- One or more of these code points combines to represent a grapheme cluster or glyph, the shapes within a font that we informally call "characters".
- Modern font formats such as TrueType and OpenType contain encoding tables which map code points to the glyphs the font file contains.
LuaLaTeX and XeLaTeX use these tools to render Unicode-encoded input files (LuaLaTeX accepts UTF-8 files, while XeLaTeX is a bit more flexible and also accepts UTF-16 and UTF-32) into PDF documents.
TeX encodings
[edit | edit source]The original TeX and LaTeX, designed long before the advent of Unicode, use a very different scheme. When using latex or pdflatex, you must choose an input encoding, which the engine uses to interpret your file, and an output encoding, which the engine uses to map your inputs to glyphs. The default font encoding is OT1, the encoding of the original Computer Modern 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 correct, this approach has some caveats compared to Unicode-based approaches:
- It prevents automatic hyphenation from working inside words containing accented characters.
- Searches for words with accents in PDFs will fail.
- Extracting (e.g., via copy-paste) the umlaut 'Ä' via a PDF viewer actually extracts the two characters '
"A
'. - Some Latin letters cannot be created with this approach, to say nothing about letters of non-Latin alphabets such as Greek or Cyrillic.
To overcome these shortcomings, several other 8-bit output encodings were created. Extended Cork (EC) fonts in T1 encoding contains letters and punctuation characters for most European languages that use Latin alphabets. 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 different fonts support different output encodings. The default Computer Modern font does not support T1, for example. 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.
If after using T1 you find yourself with very low quality fonts, it is because there is no appropriate font installed on your system. Install either cm-super or lmodern. This is a very common error! |
The fontenc package tells LaTeX what font encoding to use. Font encoding is set with:
\usepackage['encoding']{fontenc}
|
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:
\usepackage[T1]{fontenc}
\usepackage{lmodern}
|
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.
PDF fonts and properties
[edit | edit source]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.
References
[edit | edit source]- ↑ Matthew Butterick. "Bold or italic". Practical Typography.
- ↑ Matthew Butterick. "Underlining". Practical Typography.
- ↑ http://mirrors.ctan.org/macros/unicodetex/latex/fontspec/fontspec.pdf
- ↑ Matthew Butterick. "Alternate figures". Practical Typography.
List Structures
[edit | edit source]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 | edit source]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:
\begin{list_type}
\item {The first item}
\item The second item
\item The third etc \ldots
\end{list_type}
|
All three of these types of lists can have multiple paragraphs per item: just type the additional paragraphs in the normal way, with a blank line between each. So long as they are still contained within the enclosing environment, they will automatically be indented to follow underneath their item. Item content could be in the curly brackets for reading convenience of long items.
Try out the examples below, to see what the lists look like in a
real document.
\documentclass{article}
\usepackage{blindtext}
\begin{document}
\begin{itemize}
\item \blindtext
\item \blindtext
\end{itemize}
\begin{enumerate}
\item \blindtext
\item \blindtext
\end{enumerate}
\begin{description}
\item [Ant] \blindtext
\item [Elephant] \blindtext
\end{description}
\end{document}
|
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.
\begin{enumerate}
\item The first item
\begin{enumerate}
\item Nested item 1
\item Nested item 2
\end{enumerate}
\item The second item
\item The third etc \ldots
\end{enumerate}
|
Some special lists
[edit | edit source]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.
\documentclass[twocolumn]{article}
\usepackage{blindtext}
\usepackage{scrextend}
\addtokomafont{labelinglabel}{\sffamily}
\begin{document}
\blindtext
\begin{labeling}{alligator}
\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
\end{labeling}
\end{document}
|
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.
\documentclass[twocolumn]{article}
\usepackage{blindtext}
\usepackage[inline]{enumitem}
\usepackage{xcolor}
\begin{document}
\blindtext Coco likes fruit. Her favorites are:
\begin{enumerate*}[label={\alph*)},font={\color{red!50!black}\bfseries}]
\item bananas
\item apples
\item oranges and
\item lemons.
\end{enumerate*}
\blindtext
\end{document}
|
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.
\documentclass[12pt]{article}
\usepackage{tasks}
\usepackage{exsheets}
\SetupExSheets[question]{type=exam}
\begin{document}
\begin{question}
Which one of the entries does not fit with the others?
\begin{tasks}(4)
\task mercury
\task iron
\task lead
\task zinc
\end{tasks}
\end{question}
\settasks{
label=(\roman*),
label-width=4ex
}
\begin{question}
What is a funkyton?
\begin{tasks}(2)
\task A dancing electron
\task A dancing proton
\task A dancing neutron
\task A Dixie Dancing Duck
\end{tasks}
\end{question}
\end{document}
|
Customizing lists
[edit | edit source]When dealing with lists containing just a few words per item, the standard lists often take up too much space. Package enumitem provides you a simple interface to customize the appearance of lists.
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
.
\documentclass[twocolumn]{article}
\usepackage{blindtext}
\usepackage{enumitem}
\begin{document}
\blindtext
\begin{itemize}
\item more work
\item more responsibility
\item more satisfaction
\end{itemize}
\blindtext
\newpage
\blindtext
\begin{itemize}[noitemsep]
\item more work
\item more responsibility
\item more satisfaction
\end{itemize}
\blindtext
\end{document}
|
An example for alignment and the width of the label.
\documentclass[twocolumn]{article}
\usepackage{blindtext}
\usepackage{enumitem}
\begin{document}
\blindtext Coco likes fruit. Her favourites are:
\begin{description}[align=left]
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail
\end{description}
\begin{description}[align=right]
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail
\end{description}
\begin{description}[align=right,labelwidth=3cm]
\item [Kate] some detail
\item [Christina]some detail
\item [Laura]some detail
\end{description}
\blindtext
\end{document}
|
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 | edit source]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:
\usepackage[ampersand]{easylist}
|
The easylist environment will default to enumerations.
\begin{easylist}
& Main item~:
&& Sub item.
&& Another sub item.
\end{easylist}
|
It features predefined styles which you can set as optional argument.
\begin{easylist}[itemize]
% ...
\end{easylist}
|
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:
\begin{easylist}[enumerate]
\ListProperties(Style2*=,Numbers=a,Numbers1=R,FinalMark={)})
& Main item~:
&& Sub item.
&& Another sub item.
\end{easylist}
|
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:
\usepackage{amssymb}
\ListProperties(Hide=100, Hang=true, Progressive=3ex, Style*=-- ,
Style2*=$\bullet$ ,Style3*=$\circ$ ,Style4*=\tiny$\blacksquare$ )
% ...
\begin{easylist}
& Blah
& Blah
&& Blah
&&& Blah
&&&& Blah
&&&&& Blah
\end{easylist}
|
– 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$ )}
\newcommand\myenumerate{\ListProperties(Space=2\baselineskip)}
% ...
\begin{easylist} \myitemize
& Blah
\end{easylist}
|
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:
\Activate
\begin{easylist}
& ...
\end{easylist}
\Deactivate
|
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:
\begin{frame}[fragile]
...
\begin{easylist}[itemize]
...
\end{easylist}
...
\end{frame}
|
Special Characters
[edit | edit source]This chapter assumes you are using the latex or pdflatex engines and need to concern yourself with TeX's various encodings. lualatex and xelatex, on the other hand, accept Unicode input and can usually typeset documents using the correct glyphs without further user intervention. See the Fonts chapter's discussion of encoding for additional information. |
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 the lowercase letters a–z, uppercase letters A-Z, figures 0–9, and English punctuation marks.
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 | edit source]TeX uses ASCII by default. But 128 characters is not enough to support non-English languages. TeX has its own way of doing 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 that 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.
\usepackage[utf8]{inputenc}
|
inputenc [1] package tells LaTeX what the text encoding format of your .tex files is.
If you check the character encoding (e.g. using the Unix file command), be sure that your file contains at least one special character, otherwise it will be recognized as ASCII (which is logical since UTF-8 is a superset of ASCII). |
The inputenc package allows the user to change the encoding within the document as well — by means of the command \inputencoding{'encoding name'}
.
\usepackage[utf8]{inputenc}
% ...
% In this area
% The UTF-8 encoding is specified.
% ...
\inputencoding{latin1}
% ...
% Here the text encoding is specified as ISO Latin-1.
% ...
\inputencoding{utf8}
% Back to the UTF-8 encoding.
% ...
|
Extending the support
[edit | edit source]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 include, for example:
ŷ Ŷ ũ Ũ ẽ Ẽ ĩ Ĩ
In such case, you may try 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:
\DeclareUnicodeCharacter{0177}{\^y}
|
Now inputting ŷ will effectively print ŷ.
Escaped codes
[edit | edit source]In addition to direct UTF-8 input, LaTeX supports the composition of special characters as well. 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) |
{\i} |
ı | dotless i (i without tittle) |
Older versions of LaTeX would not remove the dot on top of the i and j letters when adding a diacritic. To correct this, one had to use the dotless version of these letters, by typing \i
and \j
. For example:
\^{\i}
should be used for i-circumflex î;\"{\i}
should be used for i-umlaut ï.
However, current versions of LaTeX do not need this anymore (and may, in fact, crash with an error).
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 | edit source]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:
\textless
\textgreater
|
Euro € currency symbol
[edit | edit source]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):
\usepackage[official]{eurosym}
|
then you can insert it with the \euro{}
command. Finally, if you want a euro symbol that matches with the current font style (e.g., bold, italics, etc.) you can use a different option:
\usepackage[gen]{eurosym}
|
again you can insert the euro symbol with \euro{}
.
Alternatively, you can use the marvosym package which also provides the official euro symbol.
\usepackage{marvosym}
% ...
\EUR{}
|
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.
\DeclareUnicodeCharacter{20AC}{\euro{}}
% or
\DeclareUnicodeCharacter{20AC}{\EUR{}}
|
Complete example:
\usepackage[utf8]{inputenc}
\usepackage{marvosym}
\DeclareUnicodeCharacter{20AC}{\EUR{}}
|
Degree symbol for temperature and math
[edit | edit source]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:
\usepackage{amsmath}
\usepackage{siunitx}
%...
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.
\usepackage{textcomp}
%...
A $45$\textdegree angle.
|
For temperature, you can use the same command or opt for the gensymb package and write
\usepackage{gensymb}
\usepackage{textcomp}
%...
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 in terms of font quality, we recommend the use of an appropriate font, like lmodern:
\usepackage[utf8]{inputenc}
\usepackage{lmodern}
\usepackage{textcomp}
% ...
17\,°C
17\,℃ % best
|
Other symbols
[edit | edit source]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 |
---|---|---|
\%
|
% | |
\$
|
$ | |
\{
|
{ | |
\_
|
_ | |
\P
|
¶ | |
\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 ZapfDingbats 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:
In special environments
[edit | edit source]Math mode
[edit | edit source]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 | edit source]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 | edit source]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 appropriate modifier, like Alt Gr. It highly depends on the selected layout+variant, so we suggest you to play a bit with your keyboard, preceding every key and dead key with the Alt Gr modifier.
In Windows, you can hold Alt and type a <codepoint> to get a desired character. For example,
<Alt> + 0252
will print the German letter ü.
External links
[edit | edit source]- A few other LaTeX accents and symbols
- NASA GISS: Accents
- The Comprehensive LATEX Symbol List
- Comprehensive List of Mathematical Symbols
- PDF document with a lengthy list of symbols provided by various packages
- Search LaTeX symbols by drawing them
Notes and References
[edit | edit source]- ↑ For a detailed information on the package, see complete specifications written by the package's authors.
Internationalization
[edit | edit source]LaTeX requires some additional configuration to typeset documents in languages other than English. In addition, many scripts require LuaTeX, which is currently the recommended engine in newly created documents[1], or XeTeX.
There are currently two packages providing international language support, namely, Babel and Polyglossia:
- Babel[2] works with the three main engines, namely, pdfTeX, LuaTeX and XeTeX. Depending on the engine the number of supported languages (with various levels of coverage) goes from about 170 to 300, covering about 45 scripts, and new ones can be declared easily from scratch. It also provides partial support for Plain TeX.
- Polyglossia was devised as an alternative to Babel for the now discouraged XeTeX (although provides partial support for LuaTeX, but not for pdfTeX). It supports about 90 languages, covering about 30 scripts.
Both packages cover the major languages around the World (French, Spanish, Arabic, Chinese, Japanese, Thai, Hindi, Marathi, etc.) and handle the following tasks:
- Fonts
- Assigning a font to each non-Latin language. Traditional LaTeX requires setting an appropriate font encoding. In Unicode engines, both `babel` and `polyglossia` rely on the advanced OpenType font features provided by the 'fontspec' package. While 'babel' offers a high-level interface that automatically sets the language and script, 'polyglossia' depends on standard calls to 'fontspec' and they must be set by hand. With Babel + LuaTeX the font can be switched automatically based on script. See also the discussion of fontspec in the Fonts chapter.
- Linebreaking, justification and hyphenation
- Activating for each script and language the corresponding line breaking algorithm. In the case of hyphenated languages, loading the language-specific hyphenation patterns. Babel and Polyglossia provide basic line breaking for CJK scripts. Babel provides non-standard hyphenation, like “ff” → “ff-f”, repeated hyphens, and ranked rules, and there is also some tentative support for Arabic and Tibetan justificacion.
- Cultural elements
- Translating document labels (like “chapter”, “figure”, “bibliography”), as well as formatting dates according to language-specific conventions and formatting numbers for languages that have their own numbering system. Polyglossia can generate the current date in the Hebrew, Islamic (Civil) and Persian calendars; Babel supports in addition Islamic Umm al-Qura, Coptic, Ethiopic, Chinese, and Buddhist.
- Bidirectional typesetting
- Supporting documents that contain right to left scripts. Babel + LuaTeX uses an algorithm based on the Unicode one, which changes the direction automatically. Layout elements such as tables, margins and so on must be reversed too, and this is done by Babel with LuaTeX to a great extent. With XeTeX, both Babel and Polyglossia rely on the bidi package, which requires explicit markup to change the direction.
- Typographical rules and transliterations
- Performing miscellaneous transformation both at the character level (like transliterations) as well as at the typographical level (like inserting spaces or penalties at appropriate places). Babel with LuaTeX can do this automatically by means of “transforms”; with XeTeX this can be done to some extent (both Babel and Polyglossia), while in 8-bit engines many of them must be done by hand.
With Babel, LaTeX ≥ 2018-04-01, and a monolingual document in UTF-8 encoding (which is the recommended encoding), all you need in many European languages is something like, for example:
\documentclass[french]{article}
\usepackage[T1]{fontenc} % <- With XeTeX or LuaTeX, delete this line
\usepackage{babel}
\begin{document}
Plus ça change, plus c'est la même chose!
\end{document} |
In addition, there are some specialized frameworks for languages like Japanese, Korean or Chinese, described below.
Encodings
[edit | edit source]Unicode engines
[edit | edit source]When using the xelatex or lualatex engines, many of the problems described below are solved for you. Input files are assumed to be UTF-8 (XeLaTeX also accepts UTF-16 and UTF-32), and the engine automatically maps Unicode characters to their glyphs in the TrueType or OpenType fonts you selected for your document. (This is, of course, assuming those fonts contain the glyphs you need, so you must ensure that your fonts support the languages you are using.)
8-bit engines
[edit | edit source]With engines not supporting Unicode internally (latex or pdflatex), LaTeX must handle two fundamental problems:
- Mapping the bytes of your input file into the characters of the language(s) you want to use.
- Mapping those characters to their glyphs in the fonts your document uses.
With them, you must tell LaTeX which encoding to use for your input files, and what "output" encoding it should use to map characters to their glyphs in the fonts. In most cases (especially for multilingual documents), UTF-8 is an optimal input encoding, which is currently the default encoding.
For most Latin languages, T1 is the desired output encoding, and can be set with:
\usepackage[T1]{fontenc} |
Other output encodings for specific languages are shown below.
For additional information, see the discussion of encoding in the Fonts chapter, as well as the Special Characters chapter.
Babel
[edit | edit source]The core package babel supports the 3 main engines (PDFLaTeX, LuaLaTeX and XeLaTeX). There are two ways to specify the document languages. One of them is as arguments to the package when it is loaded:
\usepackage[language]{babel} |
Another approach is making the language a global option in order to let other packages detect and use it:
\documentclass[language]{article}
\usepackage{babel} |
Finally, babel provides total or partial support for about 300 languages with a set of ini files, which are accessed with \babelprovide
. This command can be used to define easily your own language from scratch, too. Names are normalized to those in the Unicode CLDR.
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 (with LuaLaTeX, however, hyphenation rules can be loaded when the document is being typeset). 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:
\usepackage[languageA,languageB]{babel} |
Short texts in a secondary language does not require an explicit declaration in the preamble, because babel supports lazy loading of languages. Just select it as explained in what follows and the basic declarations will be loaded on the fly.
The last language in the option list will be active (i.e. languageB), and you can use the command
\selectlanguage{languageA} |
to change the active language (when the document begins, with \begin{document}
, the main language is automatically selected). 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:
\begin{otherlanguage}{languageB}
Text in language B. This environment switches all language-related definitions, like the language
specific names for figures, tables etc. to the other language.
\end{otherlanguage} |
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 babel manual provides much more information on these and many other options.
Font management
[edit | edit source]If you are using XeTeX or LuaTeX, Babel supports OpenType fonts with fontspec. To ease font handling, it provides the macro \babelfont
, which switches the font across languages and sets the OpenType ‘language system’ (ie, language and script). Let us assume you are setting up a document in Swedish, with some words in Hebrew, with a font suited for both languages:
\babelfont{rm}{FreeSerif} |
If, on the other hand, you have to resort to different fonts, you would say:
\babelfont{rm}{Iwona}
\babelfont[hebrew]{rm}{FreeSerif} |
Also, with version >=3.38 the locale identifiers (\language and \localeid) and the fonts can be switched without explicit markup, depending on the script (only LuaTeX). In the following example, bidi=basic
switches the direction, and onchar=ids fonts
switches the identifiers and the font:
\documentclass{article}
\usepackage[swedish, bidi=basic]{babel}
\babelprovide[import, onchar=ids fonts]{hebrew}
\babelfont{rm}{Iwona}
\babelfont[hebrew]{rm}{FreeSerif}
\begin{document}
Svenska עִבְרִית svenska.
\end{document} |
Bidirectional texts
[edit | edit source]Babel provides basic support fo bidi texts. The package option may take three values, namely, default
, basic-r
, and basic
. With bidi=basic
RTL and LTR text can be mixed without explicit markup (only LuaTeX).
Customization
[edit | edit source]Babel
provides tools to customize the behavior of languages. The most common requirement is modifying the default captions like the chapter name, because the strings defined for each language not always fit some editorial or personal preferences. The command \setlocalecaption
is provided for this purpose. For example:
\setlocalecaption{spanish}{contents}{Contenidos} |
Formerly, the only way to customize the captions was with something like \addto\captionsspanish{\renewcommand{\contentsname}{Contenidos}}
. According to the babel
manual, this low level interface is not recommended.
Multilingual versions
[edit | edit source]It is possible in LaTeX to typeset the content of one document in several languages and to choose upon compilation which language to output in predefined strings (chapter name, date, etc.). 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
text
\begin{de}
German text
\end{de}
text |
There is a clear drawback to this feature, namely, the ‘prefix’ \text... is heavily overloaded in LaTeX and conflicts with existing macros may arise. The babel manual recommends to to stick to the default selectors or to define your own alternatives.
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:
\IfLanguageName{ngerman}{Hallo}{Hello}
This allows to easily distinguish between two languages without the need of defining own commands. Another approach for localized strings is translator.
Polyglossia
[edit | edit source]When using XeLaTeX or LuaLaTeX, polyglossia provides an alternative to the core babel package for international language support, as described in its manual.
The original aim was to be compatible with babel, but there is a number of differences. For example, the standard mechanism in LaTeX to declare languages, via package or class options, is not recognized, and the user must rely on a set of new commands, as shown in the example. Unlike babel, secondary languages must be always explicitly declared, because polyglossia doesn't support lazy loading. It also adds the concept of ‘language variant’, while in babel, all locales are treated on an equal footing. Not only languages are declared in a non standard way, but also a new way to switch languages has been devised, with commands like \textenglish or \textlang. Font are set with standard `fontspec` commands and no higher level interface is provided.
To use polyglossia, load it in your preamble and specify the languages you will be using, along with any language-specific options you wish.
If, for example, we have a document with American English as the main language, and some short texts in French, Bulgarian and Greek, you might use:
\documentclass{article}
\usepackage{polyglossia}
\setdefaultlanguage[variant=american]{english}
\setotherlanguages{french, bulgarian, greek}
\newfontfamily\bulgarianfont
{NewComputerModern10}[Script=Cyrillic,Language=Bulgarian]
\newfontfamily\greekfont
{NewComputerModern10}[Script=Greek,Language=Greek]
\begin{document}
English. \textlang{french}{French}. \textlang{bulgarian}{Български}.
\textlang{greek}{Ελληνικά}.
\end{document} |
As a comparison, here is the code with `babel`:
\documentclass{article}
\usepackage[american]{babel}
\babelfont[*cyrillic, *greek]{rm}{NewComputerModern10}
\begin{document}
English. \foreignlanguage{french}{French}.
\foreignlanguage{bulgarian}{Български}. \foreignlanguage{greek}{Ελληνικά}.
\end{document} |
Specific languages
[edit | edit source]Here is a collection of language-specific suggestions. If you have experience in a language not listed below, please add some notes about it. Some of the methods described in this chapter may be useful when dealing with non-English author names in bibliographies.
Most of the following assumes you are using babel, but polyglossia supports some of the same commands, although their behavior may be different. |
Arabic script
[edit | edit source]Documents in the Arabic script, including Arabic, Persian, Urdu, Pashto, Kurdish, Uyghur, etc., are best typeset with either XeTeX or LuaTeX. An example with babel and LuaTeX follows (rendering by the browser may be different from an editor):
\documentclass{article}
\usepackage[bidi=basic]{babel}
\babelprovide[import, main]{arabic}
\babelfont{rm}{FreeSerif}
\begin{document}
وﻗﺪ ﻋﺮﻓﺖ ﺷﺒﻪ ﺟﺰﻳﺮة اﻟﻌﺮب ﻃﻴﻠﺔ اﻟﻌﺼﺮ اﻟﻬﻴﻠﻴﻨﻲ )اﻻﻏﺮﻳﻘﻲ( ﺑـ
Arabia أو Aravia )ﺑﺎﻻﻏﺮﻳﻘﻴﺔ Αραβία (، اﺳﺘﺨﺪم اﻟﺮوﻣﺎن ﺛﻼث
ﺑﺎدﺋﺎت ﺑـ “Arabia” ﻋﻠﻰ ﺛﻼث ﻣﻨﺎﻃﻖ ﻣﻦ ﺷﺒﻪ اﻟﺠﺰﻳﺮة اﻟﻌﺮﺑﻴﺔ، إﻻ أﻧﻬﺎ
ﺣﻘﻴﻘﺔً ﻛﺎﻧﺖ أﻛﺒﺮ ﻣﻤﺎ ﺗﻌﺮف ﻋﻠﻴﻪ اﻟﻴﻮم.
\end{document} |
With XeTeX, you may set bidi=bidi
, but mixed LR and RL text must be marked up explicitly. The same applies to polyglossia.
babel with LuaTeX provides partial and tentative support for Arabic justification based on kashida (with the ARABIC TATWEEL Unicode character) or on the ‘justification alternatives’ OpenType table (jalt).
An alternative package for LuaTeX is arabluatex, which is an extension for LuaTeX of arabtex, described below. For XeTeX there is arabxetex.
In 8-bit engines, they can be typeset in a number of ways, one of the oldest being arabtex. Add the following code to your preamble:
\usepackage{arabtex} |
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
\usepackage{cmap}
\usepackage[LAE,LFE]{fontenc}
\usepackage[arabic,farsi]{babel} |
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.
Armenian
[edit | edit source]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 or LuaLaTeX.
Once the text editor is set up to compile with XeLaTeX or LuaLaTeX, the fontspec package can be used to write in Armenian:
\usepackage{fontspec}
\setmainfont{DejaVu Serif} |
or
\usepackage{fontspec}
\setmainfont{Sylfaen} |
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 Unicode engines.
Cyrillic script
[edit | edit source]Currently the most convenient way to typeset Cyrillic texts is with XeTeX or LuaTeX in the UTF-8 encoding. An example for Russian with these engines, which do not require encoding transformations because everything is done directly in that encoding, is:
\documentclass{article}
\usepackage[russian]{babel}
\babelfont{rm}{DejaVu Serif}
\begin{document}
Россия, находящаяся на пересечении множества культур, а также
с учётом многонационального характера её населения, — отличается
высокой степенью этнокультурного многообразия и способностью к
межкультурному диалогу.
\end{document} |
Support for Cyrillic in non-Unicode engines is based on standard LaTeX mechanisms plus the fontenc and inputenc packages. babel includes support for the T2* encodings and for typesetting Bulgarian, Russian and Ukrainian texts using Cyrillic letters[3] with non-Unicode engines. 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:
\usepackage{amsmath,amsthm,amssymb}
\usepackage{mathtext}
\usepackage[T1,T2A]{fontenc}
\usepackage[english,bulgarian,russian,ukrainian]{babel} |
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
\Asbuk
\asbuk |
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
\enumBul
\enumLat
\enumEng |
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" [4] for a method to type Cyrillic letters directly from the keyboard using a different distribution.
Chinese
[edit | edit source]Typesetting Chinese texts (and, in general, CJK script ones) is best done with a complete framework, like CJK o xeCJK, although for short texts or a few words in horizontal typesetting babel with XeTeX and LuaTeX could be enough, with basic line breaking.
CJK Package
[edit | edit source]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.
\documentclass{article}
\usepackage{CJK}
\begin{document}
\begin{CJK}{UTF8}{gbsn}
你好
You can mix Latin letters and Chinese.
\end{CJK}
\end{document} |
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)
In CTeX distribution (which has been outdated), six more fonts for simplified Chinese are included, corresponding to default Windows fonts:
- song (宋体, Simsun)
- hei (黑体, Simhei)
- fang (仿宋, STFangSong)
- kai (楷体, STKaiti)
- li (隶书, SimLi)
- you (幼圆, SimYou)
xeCJK Package
[edit | edit source]When using the XeTeX engine, there is another package called xeCJK, which is based on fontspec and offers similar interface to CJK package.
When using the package, one can define CJK fonts like this:
\documentclass{article}
\usepackage{xeCJK}
\setCJKmainfont{FZSSK.ttf} % use Foundertype's Chinese font, which has a free license
\begin{document}
你好
You can still mix Latin letters and Chinese!
\end{document} |
Czech
[edit | edit source]Czech is fine using
\usepackage[czech]{babel} |
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
.
Copying and searching in PDF
[edit | edit source]Although czech letters with diacritical sign are displayed correctly, they are not copy-able or search-able in PDF files generated with pdfLaTeX with just command above. Using package cmap solves this for some fonts, for others is also neccessary to use command glyphtounicode.
Font | (no additional command) | \usepackage{cmap} |
\usepackage[resetfonts]{cmap} |
\usepackage{cmap}
\input{glyphtounicode}
\pdfgentounicode=1 |
---|---|---|---|---|
\usepackage{lmodern} |
ešcržýáíédtnúuŠCRŽÁÚ | ěščřžýáíéďťňúůŠČŘŽÁÚ | ěščřžýáíéďťňúůŠČŘŽÁÚ | ěščřžýáíéďťňúůŠČŘŽÁÚ |
\usepackage{ebgaramond} |
ešcržýáíédtnúuŠCRŽÁÚ | ešcržýáíédtnúuŠCRŽÁÚ | ešcržýáíédtnúuŠCRŽÁÚ | ěščřžýáíéďťňúůŠČŘŽÁÚ |
Devanagari and other Indic scripts
[edit | edit source]The Devanagari script is used by many languages, including Marathi, Pāḷi, Sanskrit, Hindi, Nepali, Bodo, Konkani, Prakrit. Here is an example for Hindi with babel, for both XeTeX and LuaTeX:
\documentclass{article}
\usepackage[hindi, provide=*]{babel}
\babelfont{rm}{FreeSerif}
\begin{document}
देवनागरी एक भारतीय लिपि है जिसमें अनेक भारतीय भाषाएँ तथा कई विदेशी
भाषाएँ लिखी जाती हैं।
\end{document} |
Other Indic scripts have a similar setup (Malayalam, Bengali, Sinhala, Telugu, Tamil, Kannada, Assamese, Punjabi, etc.).
If any additional features are required, you need an alternative approach, as illustrated in the following example for Bangla, which sets the option mapdigits for the Arabic digits to be converted to the local ones (only LuaTeX).
\documentclass{article}
\usepackage{babel}
\babelprovide[import, main, mapdigits]{bengali}
\babelfont{rm}{FreeSerif}
\begin{document}
গাইতে গাইতে গায়েন।
\end{document} |
Mapping the digits is accomplished in XeTeX at the font level, with the option Mapping=, like:
\babelfont{rm}[Mapping=bengalidigits]{FreeSerif} |
This is actually a XeTeX feature and doesn't require babel. It can be used directly with fontspec.
Support in pdfTeX is based mainly on the velthuis package. An alternative for XeTeX is latexbangla, which relies on polyglossia.
Finnish
[edit | edit source]Finnish language hyphenation is enabled with:
\usepackage[finnish]{babel} |
This will also automatically change document language (section names, etc.) to Finnish.
French
[edit | edit source]As of version 3.0 of babel-french, it is advised to choose the language as a global option with the following command[5]:
\documentclass[french]{article}
\usepackage{babel} |
Formerly, you could load French language support with the following command:
\usepackage[frenchb]{babel} |
or
\usepackage[francais]{babel} |
There are multiple options for typesetting French documents, depending on the flavor of French: french 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 french
.
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 has 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[french]{babel}
\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 \frenchsetup
command. For more information on what the french 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.
German
[edit | edit source]You can load German language support using either one of the two following commands (pdfTeX, XeTeX and LuaTeX are supported).
For traditional ("old") German orthography use
\usepackage[german]{babel} |
or for reform ("new") German orthography use
\usepackage[ngerman]{babel} |
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.
"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
\usepackage[output-decimal-marker={,}]{siunitx}
% ...
\num{0,5} |
|
Greek
[edit | edit source]This is the preamble you need to write in the Greek language.
\usepackage[greek]{babel} |
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.
Modern Monotonic Greek, as well as Polytonic and Ancient Greek are supported.
If you need a language in the Latin script and you are using LuaTeX, you can switch automatically the font in the following way, with no explicit markup:
\documentclass{book}
\usepackage[portuguese, greek]{babel}
\babelprovide[onchar=ids fonts]{portuguese}
\babelfont{rm}{FreeSerif}
\babelfont[portuguese]{rm}{DejaVu Sans}
\begin{document}
abelha -- μελισσα
\end{document} |
There is a dedicated package for XeTeX named xgreek.
Hungarian
[edit | edit source]Use the following lines:
\usepackage[magyar]{babel} |
More information in hungarian.
Icelandic and Faroese
[edit | edit source]The following lines can be added to write Icelandic text:
\usepackage[icelandic]{babel} |
This changes text like Part into Hluti. It makes additional commands available:
"` or \glqq | „ |
\grqq | “ |
\TH | Þ |
\th | þ |
\DH | Ð |
\dh | ð |
To make special characters such as Þ and Æ become available just add:
\usepackage[T1]{fontenc} |
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
[edit | edit source]Italian is well supported by LaTeX. Just add
\usepackage[italian]{babel} |
at the beginning of your document and the output of all the commands will be translated properly.
Norwegian
[edit | edit source]Norwegian is well supported by LaTeX. Just add
\usepackage[norsk]{babel} |
at the beginning of your document and the output of all the commands will be translated properly.
Japanese
[edit | edit source]jlreq
[edit | edit source]The package provides the class file and JFM (Japanese font metric) files for LuaTeX-ja / pLaTeX / upLaTeX. This aims to implement Requirements for Japanese Text Layout.
upTeX, pTeX
[edit | edit source]There is a variant of TeX intended for Japanese named upTeX, which supports vertical typesetting.
luatexja
[edit | edit source]Another possible way to write in japanese is to use Lualatex and the luatex-ja package. Adapted example from the Luatexja documentation :
\documentclass{ltjsarticle}
\usepackage{luatexja} % This line is unnecessary when using ltjclasses or ltjsclasses.
\begin{document}
\section{はじめてのLua\TeX-ja}
ちゃんと日本語が出るかな?
\subsection{出たかな?}
長い文章を入力するとちゃんと右端のところで折り返されるかな?
大丈夫そうな気がするけど.ちょっと不安だけど何事も挑戦だよね.
\end{document} |
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
\documentclass[10pt,a4paper]{article}
\usepackage{fontspec}
\setmainfont[Numbers={OldStyle,Proportional}]{Arno Pro} %setup of western font
\usepackage{luatexja}
\usepackage{luatexja-fontspec}%needed to call \setmainjfont bellow
\setmainjfont[BoldFont=KozGoPr6N-Bold]{KozGoPr6N-Regular} %setup of japanese font
%***********************************
\begin{document}
It is a test to show japanese and english mix. テスト中です。どうですか皆さん。
\end{document} |
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 uses UTF-8 by default.
luatex-ja can collaborate with babel. For example:
\documentclass{ltjbook}
\usepackage[ngerman,japanese]{babel} |
For short Japanese texts (a few words or a few paragraphs) in a document in another language, babel (≥3.31) with luatex could be enough; eg:
\usepackage[ngerman]{babel}
\babelprovide[import]{japanese}
\babelfont[japanese]{rm}{IPAMincho} |
For hyperref package to show the Table of Contents correctly, the encoding has to be explicitly specified.
\usepackage[unicode=true]{hyperref} |
CJK, XeCJK, bxcjkjatype
[edit | edit source]Another (but old) possible Japanese support is made available thanks to the CJK or XeCJK 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.
\documentclass{article}
\usepackage{CJK}
\begin{document}
\begin{CJK}{UTF8}{min}
こんにちは
You can mix latin letters as well as hiragana, katakana and kanji.
\end{CJK}
\end{document} |
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 bxcjkjatype package provides a working configuration of the CJK package, suitable for Japanese typesetting of moderate quality. Moreover, it facilitates use of the CJK package for pLATEX users, by providing commands that are similar to those used by the pLATEX kernel and some other packages used with it.
\documentclass[pdflatex,ja=standard]{bxjsarticle}
\begin{document}
吾輩は猫である。名前はまだ無い。
どこで生れたかとんと見当がつかぬ。
何でも薄暗いじめじめした所で
ニャーニャー泣いていた事だけは記憶している。
吾輩はここで始めて人間というものを見た。
\end{document} |
Korean
[edit | edit source]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 http://jshin.net/faq 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:
\usepackage{hangul} |
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.
\usepackage{hfont} |
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
\usepackage{kotex} |
Persian script
[edit | edit source]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:
\usepackage{xepersian} |
Moreover, Arabic script can be used to type Persian as illustrated in the corresponding section.
Polish
[edit | edit source]If you plan to use Polish in your encoded document, use the following code:
\usepackage{polski}
\usepackage[polish]{babel} |
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.
Connectives
[edit | edit source]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. |
Babel (>=3.58) with LuaTeX provides a transform for this purpose, without explicit markup, which is activated with:
\babelprovide[transforms = oneletter.nobreak]{polish} |
Numerals
[edit | edit source]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:
\renewcommand\thechapter{\arabic{chapter}.}
\renewcommand\thesection{\arabic{chapter}.\arabic{section}.}
\renewcommand\thesubsection{\arabic{chapter}.\arabic{section}.\arabic{subsection}.}
\renewcommand\thesubsubsection{\arabic{chapter}.\arabic{section}.\arabic{subsection}.\arabic{subsubsection}.} |
For articles:
\renewcommand\thesection{\arabic{section}.}
\renewcommand\thesubsection{\arabic{section}.\arabic{subsection}.}
\renewcommand\thesubsubsection{\arabic{section}.\arabic{subsection}.\arabic{subsubsection}.} |
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:
\documentclass{mwart}
\usepackage[polish]{babel}
\usepackage{polski}
\begin{document}
Pójdź kińże tę chmurność w głąb flaszy.
\end{document} |
Full documentation for those classes is available at http://web.archive.org/web/20040609034031/http://www.ci.pwr.wroc.pl/~pmazur/LaTeX/mwclsdoc.pdf (Polish).
Indentation
[edit | edit source]It may be customary (depending on publisher) to indent the first paragraph in sections and chapters:
\usepackage{indentfirst} |
Hyphenation and typography
[edit | edit source]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:
\brokenpenalty=1000 |
To adjust penalties for leaving widows and orphans (clubs in TeX nomenclature) use those commands:
\clubpenalty=1000
\widowpenalty=1000 |
Commas in math
[edit | edit source]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.
\usepackage{icomma} |
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 | edit source]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).
Portuguese
[edit | edit source]Add the following code to your preamble:
\usepackage[portuguese]{babel} |
You can substitute the language for brazilian portuguese by choosing brazilian or brazil.
Slovak
[edit | edit source]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:
\usepackage[slovak]{babel}
\usepackage[T1]{fontenc} |
Spanish
[edit | edit source]Include the appropriate Babel option:
\usepackage[spanish]{babel} |
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:
\def\spanishoptions{mexico}
\usepackage[spanish]{babel} |
\usepackage[spanish,mexico]{babel} |
On average, the former syntax should be preferred, as the latter is not recognized by some 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 formerly 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
\def\spanishoperators{sen} |
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.
Thai
[edit | edit source]Both babel (luatex and xetex) and polyglossia (only xetex) support Thai. Word division in luatex is based on the standard hyphenation mechanism, so that patterns can be modified with \babelpatterns
, while xetex relies on its own built-in mechanism. In pdftex you need an external tool for word segmentation (like swath). An example with babel (luatex and xetex) is:
\documentclass{book}
\usepackage{babel}
\babelprovide[main, import]{thai}
\babelfont{rm}{FreeSerif}
\begin{document}
ปัจจุบันข้าวและพริกเป็นส่วนประกอบสำคัญที่สุดของอาหารไทย
\end{document} |
Tibetan
[edit | edit source]One option to use Tibetan script in LaTeX is to add
\usepackage{ctib} |
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]
`babel` for `luatex` provides tentative support for justification with trailing tshegs.[10]
Vietnamese
[edit | edit source]The following preamble could be used to directly type Vietnamese (xetex or luatex).
\documentclass{article}
\usepackage{fontspec}%
\setmainfont[Ligatures=TeX]{Linux Libertine O} |
For a document written in this language:
\documentclass{article}
\usepackage[vietnamese]{babel} |
References
[edit | edit source]- ↑ Engine news from the LaTeX Project
- ↑ Babel: The multilingual framework to localize LaTeX, LuaLaTeX, XeLaTeX
- ↑ The Not So Short Introduction to LaTeX, 2.5.6 Support for Cyrillic, Maksym Polyakov
- ↑ The Not So Short Introduction to LaTeX, Bulgarian translation
- ↑ 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."
Rotations
[edit | edit source]Many DVI viewers do not support rotating of text and tables. The text will be displayed normally. You must convert your DVI file to a PDF document and view it in a PDF viewer to see the rotation in effect. Take care however that printing from those PDF files may rotate the respective page again in the same direction under certain circumstances. This behaviour can be influenced by the settings of your dvi2pdf converter, look at your manual for further information. |
The rotating package
[edit | edit source]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:
\usepackage{rotating} |
you can use three new environments:
\begin{sideways} |
it will rotate the whole argument by 90 degrees counterclockwise. Moreover:
\begin{turn}{30} |
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.
\begin{rotate}{30} |
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
\begin{sidewaysfigure} |
or
\begin{sidewaystable} |
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.
\begin{figure}
\begin{sideways}
\begin{minipage}{17.5cm}
\input{../path/to/picture}
\end{minipage}
\end{sideways}
\centering
\caption[Caption]{Caption.}
\label{pic:picture}
\end{figure} |
You can also use the \rotatebox
command. Let's rotate a tabular inside a table for example:
\begin{table}[p]
\centering
\rotatebox{90}{
\begin{minipage}{\textheight}
\begin{tabular}{ |
Options
[edit | edit source]Default is sidewaysfigures/sidewaystables are oriented depending on page number in two-sided documents (takes two passes).
The rotating package takes the following options.
- counterclockwise/anticlockwise
- In single-sided documents turn sidewaysfigures/sidewaystables counterclockwise.
- clockwise
- In single-sided documents turn sidewaysfigures/sidewaystables clockwise (default).
- figuresright
- 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).
- figuresleft
- In two-sided documents all sidewaysfigures/sidewaystables are same orientation (left of figure, table now at top of page).
The rotfloat package
[edit | edit source]When it is desirable to place the rotated table at the exact location where it appears in the source (.tex) file, rotfloat package may be used. Then one can use
\begin{sidewaystable}[H] |
just like for normal tables. The H option can not be used without this package.
Tables
[edit | edit source]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.
Introduction
[edit | edit source]LaTeX has built-in support to typeset tables and provides two environments: tabular and table. To typeset material in rows and columns, the tabular environment is needed; the optional table environment is a container for floating material similar to figure, into which a tabular environment may be included.
The table environment contains the caption and defines the float for the table, i.e., where in the document the table should be positioned and whether we want it to be displayed centered. The \caption
and \label
commands can be used in the same way as for pictures. For more information about the table environment, see the Floating with table section.
In any case, the actual content of the table is contained within the tabular environment.
The tabular environment
[edit | edit source]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 | edit source]This example shows how to create a simple table in LaTeX. It is a three-by-three table, but without any lines.
\begin{tabular}{ l c r }
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{tabular} |
|
Expanding upon that by including some vertical lines:
\begin{tabular}{ l | c | r }
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\end{tabular} |
|
To add horizontal lines to the very top and bottom edges of the table:
\begin{tabular}{ l | c | r }
\hline
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\hline
\end{tabular} |
|
And finally, to add lines between all rows, as well as centering (notice the use of the center environment - of course, the result of this is not obvious from the preview on this web page):
\begin{center}
\begin{tabular}{ l | c | r }
\hline
1 & 2 & 3 \\ \hline
4 & 5 & 6 \\ \hline
7 & 8 & 9 \\
\hline
\end{tabular}
\end{center} |
|
\begin{center}
\begin{tabular}{ | l | c | r }
\hline
1 & 2 & 3 \\ \hline
4 & 5 & 6 \\ \hline
7 & 8 & 9 \\
\hline
\end{tabular}
\end{center} |
|
\begin{tabular}{|r|l|}
\hline
7C0 & hexadecimal \\
3700 & octal \\ \cline{2-2}
11111000000 & binary \\
\hline \hline
1984 & decimal \\
\hline
\end{tabular} |
Text wrapping in tables
[edit | edit source]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 desired 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:
\documentclass{article}
\usepackage[english]{babel}
\begin{document}
Without specifying width for last column:
\begin{center}
\begin{tabular}{| l | l | l | l |}
\hline
Day & Min Temp & Max Temp & Summary \\ \hline
Monday & 11C & 22C & A clear day with lots of sunshine.
However, the strong breeze will bring down the temperatures. \\ \hline
Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells
across most of Scotland and Northern Ireland,
but rain reaching the far northwest. \\ \hline
Wednesday & 10C & 21C & Rain will still linger for the morning.
Conditions will improve by early afternoon and continue
throughout the evening. \\
\hline
\end{tabular}
\end{center}
With width specified:
\begin{center}
\begin{tabular}{ | l | l | l | p{5cm} |}
\hline
Day & Min Temp & Max Temp & Summary \\ \hline
Monday & 11C & 22C & A clear day with lots of sunshine.
However, the strong breeze will bring down the temperatures. \\ \hline
Tuesday & 9C & 19C & Cloudy with rain, across many northern regions. Clear spells
across most of Scotland and Northern Ireland,
but rain reaching the far northwest. \\ \hline
Wednesday & 10C & 21C & Rain will still linger for the morning.
Conditions will improve by early afternoon and continue
throughout the evening. \\
\hline
\end{tabular}
\end{center}
\end{document} |
You get the following output:
Note that the first table has been cropped, since the output is wider than the page width.
Manually broken paragraphs in table cells
[edit | edit source]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
:
\begin{tabular}{cc}
boring cell content & \parbox[t]{5cm}{rather long par\\new par}
\end{tabular} |
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 | edit source]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.
One can also introduce a horizontal space with hspace like this: \begin{tabular}{r@{\hspace{1in}}rr}
There are different options for the hspace length.
Space between rows
[edit | edit source]Re-define the \arraystretch
command to set the space between rows:
\renewcommand{\arraystretch}{1.5} |
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 | }
\hline\noalign{\smallskip}
\multicolumn{2}{c}{Item} \\
\cline{1-2}\noalign{\smallskip}
Animal & Description & Price (\$) \\
\noalign{\smallskip}\hline\noalign{\smallskip}
Gnat & per gram & 13.65 \\
& each & 0.01 \\
Gnu & stuffed & 92.50 \\
Emu & stuffed & 33.33 \\
Armadillo & frozen & 8.99 \\
\noalign{\smallskip}\hline
\end{tabular} |
You may also specify the skip after a line explicitly using glue after the line terminator
\begin{tabular}{ll}
\hline
Mineral & Color \\[1cm]
Ruby & red \\
Sapphire & blue \\
\hline
\end{tabular} |
Other environments inside tables
[edit | edit source]If you use some LaTeX environments inside table cells, like verbatim or enumerate:
\begin{tabular}{c c}
\hline
\begin{verbatim}
code
\end{verbatim}
& description
\\ \hline
\end{tabular} |
you might encounter errors similar to
! LaTeX Error: Something's wrong--perhaps a missing \item.
To solve this problem, change column specifier to "paragraph" (p, m or b).
\begin{tabular}{m{5cm} c} |
Defining multiple columns
[edit | edit source]It is possible to define many identically aligned columns at once using the *{num}{str}
syntax. This is particularly useful when your table has many columns.
Here is a table with six centered columns flanked by a single column on each side:
\begin{tabular}{l*{6}{c}r}
Team & P & W & D & L & F & A & Pts \\
\hline
Manchester United & 6 & 4 & 0 & 2 & 10 & 5 & 12 \\
Celtic & 6 & 3 & 0 & 3 & 8 & 9 & 9 \\
Benfica & 6 & 2 & 1 & 3 & 7 & 8 & 7 \\
FC Copenhagen & 6 & 2 & 1 & 3 & 5 & 8 & 7 \\
\end{tabular} |
Column specification using >{\cmd} and <{\cmd}
[edit | edit source]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} }%
l%
<{\end{lrbox}%
\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
\tabularnewline
\hline
Points & Addition
\tabularnewline
Spheres & Multiplication
\end{tabular} |
Note the use of \tabularnewline
instead of \\
to avoid a Misplaced \noalign
error.
@ and ! expressions
[edit | edit source]The column separator can be specified with the @{...}
or !{...}
constructs.
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. The @{...}
command kills the inter-column space and replaces it with whatever is between the curly braces. To keep the initial space, use !{...}
. To add space, use @{\hspace{''width''}}
.
Admittedly, this is not that clear, and so will require a few examples to clarify. Sometimes, it is desirable in scientific tables to have the numbers aligned on the decimal point. This can be achieved by doing the following:
\begin{tabular}{r@{.}l}
3 & 14159 \\
16 & 2 \\
123 & 456 \\
\end{tabular} |
|
The space-suppressing qualities of the @-expression actually make it quite useful for manipulating the horizontal spacing between columns. Given a basic table, and varying the column descriptions:
\begin{tabular}{ |l|l| }
\hline
stuff & stuff \\ \hline
stuff & stuff \\
\hline
\end{tabular} |
{|l|l|} | |
{|@{}l|l@{}|} | |
{|@{}l@{}|l@{}|} | |
{|@{}l@{}|@{}l@{}|} |
Aligning columns at decimal points using dcolumn
[edit | edit source]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.
\usepackage{dcolumn}
\ldots
\newcolumntype{d}[1]{D{.}{\cdot}{#1} }
%the argument for d specifies the maximum number of decimal places
\begin{tabular}{l r c d{1} }
Left&Right&Center&\mathrm{Decimal}\\
1&2&3&4\\
11&22&33&44\\
1.1&2.2&3.3&4.4\\
\end{tabular} |
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 | edit source]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.[1]
\usepackage{dcolumn}
%here we're setting up a version of the math fonts with normal x-width
\DeclareMathVersion{nxbold}
\SetSymbolFont{operators}{nxbold}{OT1}{cmr} {b}{n}
\SetSymbolFont{letters} {nxbold}{OML}{cmm} {b}{it}
\SetSymbolFont{symbols} {nxbold}{OMS}{cmsy}{b}{n}
\begin{document}
\makeatletter
\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} }
\makeatother
\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}\\
\end{tabular}
\end{document} |
Row specification
[edit | edit source]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.
\begin{tabu}{XX}
\rowfont{\bfseries\itshape\large} Header1 & Header2 \\
\hline
Cell2 & Cell2
\end{tabu} |
Spanning
[edit | edit source]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 | edit source]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| }
\hline
\multicolumn{2}{|c|}{Team sheet} \\
\hline
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 \\
\hline
\end{tabular} |
Columns spanning multiple rows
[edit | edit source]The first thing you need to do is add \usepackage{multirow}
to the preamble[2]. 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).
...
\usepackage{multirow}
...
\begin{tabular}{ |l|l|l| }
\hline
\multicolumn{3}{ |c| }{Team sheet} \\
\hline
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 \\
\hline
\end{tabular} |
The main thing to note when using \multirow
is that a blank entry must be inserted for each appropriate cell in each subsequent row to be spanned.
If there is no data for a cell, just don't type anything, but you still need the "&" separating it from the next column's data. The astute reader will already have deduced that for a table of columns, there must always be ampersands in each row (unless \multicolumn
is also used).
Spanning in both directions simultaneously
[edit | edit source]Here is a nontrivial example of how to use spanning in both directions simultaneously and have the borders of the cells drawn correctly:
\usepackage{multirow}
\begin{tabular}{cc|c|c|c|c|l}
\cline{3-6}
& & \multicolumn{4}{ c| }{Primes} \\ \cline{3-6}
& & 2 & 3 & 5 & 7 \\ \cline{1-6}
\multicolumn{1}{ |c }{\multirow{2}{*}{Powers} } &
\multicolumn{1}{ |c| }{504} & 3 & 2 & 0 & 1 & \\ \cline{2-6}
\multicolumn{1}{ |c }{} &
\multicolumn{1}{ |c| }{540} & 2 & 3 & 1 & 0 & \\ \cline{1-6}
\multicolumn{1}{ |c }{\multirow{2}{*}{Powers} } &
\multicolumn{1}{ |c| }{gcd} & 2 & 2 & 0 & 0 & min \\ \cline{2-6}
\multicolumn{1}{ |c }{} &
\multicolumn{1}{ |c| }{lcm} & 3 & 3 & 1 & 1 & max \\ \cline{1-6}
\end{tabular} |
The 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}{r}{}
& \multicolumn{1}{c}{noninteractive}
& \multicolumn{1}{c}{interactive} \\
\cline{2-3}
massively multiple & Library & University \\
\cline{2-3}
one-to-one & Book & Tutor \\
\cline{2-3}
\end{tabular} |
Controlling table size
[edit | edit source]Resize tables
[edit | edit source]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.
\usepackage{graphicx}
% ...
\resizebox{8cm}{!} {
\begin{tabular}...
\end{tabular}
} |
Resizing table including the caption
\begin{table}[h]
\resizebox{1.4\textwidth}{!}{\begin{minipage}{\textwidth}
\begin{tabular}{r|c|c|}
& \multicolumn{1}{c}{noninteractive}
& \multicolumn{1}{c}{interactive} \\
\cline{2-3}
massively multiple & Library & University \\
\cline{2-3}
one-to-one & Book & Tutor \\
\cline{2-3}
\end{tabular}
\caption[Table caption text]{Table taken from \cite[p.10]{refid} }
\label{table:name}
\end{minipage} }
\end{table} |
Alternatively you can use \scalebox{ratio}{object}
in the same way but with ratios rather than fixed sizes:
\usepackage{graphicx}
% ...
\scalebox{0.7}{
\begin{tabular}...
\end{tabular}
} |
Changing font size
[edit | edit source]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.
{\footnotesize
\begin{tabular}{| r | r || c | c | c |}
% ...
\end{tabular}
} |
\begin{table}[h]\footnotesize
\caption{Performance at peak F-measure}
\begin{tabular}{| r | r || c | c | c |}
% ...
\end{tabular}
\end{table} |
Alternatively, you can change the default font for all the tables in your document by placing the following code in the preamble:
\let\oldtabular\tabular
\renewcommand{\tabular}{\footnotesize\oldtabular} |
See Fonts for named font sizes. The table caption font size is not affected. To control the caption font size, see Caption Styles.
It is also possible to change the vertical space between rows using \renewcommand{\arraystretch}{0.8}
before \begin{tabular}
.
Colors
[edit | edit source]Alternate row colors in tables
[edit | edit source]The xcolor package provides the necessary commands to produce tables with alternate row colors, when loaded with the table option.
The command \rowcolors{<''starting row''>}{<''odd color''>}{<''even color''>}
has to be specified right before the tabular environment starts.
\documentclass{article}
\usepackage[table]{xcolor}
\begin{document}
\begin{center}
\rowcolors{1}{green}{pink}
\begin{tabular}{lll}
odd & odd & odd \\
even & even & even\\
odd & odd & odd \\
even & even & even\\
\end{tabular}
\end{center}
\end{document} |
The command \hiderowcolors
is available to deactivate highlighting 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 \\ |
or
odd & odd & odd \\ \showrowcolors |
Colors of individual cells
[edit | edit source]As above this uses the xcolor package.
% Include this somewhere in your document
\usepackage[table]{xcolor}
% Enter this in the cell you wish to color a light grey.
% NB: the word 'gray' here denotes the grayscale color scheme, not the color grey. '0.9' denotes how dark the grey is.
\cellcolor[gray]{0.9}
% The following will color the cell red.
\cellcolor{red} |
Width and stretching
[edit | edit source]We keep providing documentation for tabular* and tabularx.
The tabular* environment
[edit | edit source]This is basically a slight extension on the original tabular version, although it requires an extra argument (before the column descriptions) to specify the preferred width of the table.
\begin{tabular*}{0.75\textwidth}{ | c | c | c | r | }
\hline
label 1 & label 2 & label 3 & label 4 \\
\hline
item 1 & item 2 & item 3 & item 4 \\
\hline
\end{tabular*} |
However, that 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 | }
\hline
label 1 & label 2 & label 3 & label 4 \\
\hline
item 1 & item 2 & item 3 & item 4 \\
\hline
\end{tabular*} |
You will notice the @{...}
construct added at the beginning of the column description. Within it is the \extracolsep
command, which requires a width. A fixed width could have been used. However, by using a rubber length, such as \fill
, the columns are automatically spaced evenly.
The tabularx package
[edit | edit source]This package provides a table environment called tabularx, which is similar to the tabular* environment except that it has a new column specifier X (in uppercase). The column(s) specified with this specifier will be stretched to make the table as wide as specified, greatly simplifying the creation of tables.
\usepackage{tabularx}
% ...
\begin{tabularx}{\textwidth}{ |X|X|X|X| }
\hline
label 1 & label 2 & label 3 & label 4 \\
\hline
item 1 & item 2 & item 3 & item 4 \\
\hline
\end{tabularx} |
The content provided for the boxes is treated as for a p column, except that the width is calculated automatically. If you use the package array, you may also apply any >{\cmd}
or <{\cmd}
command to achieve specific behavior (like \centering
, or \raggedright\arraybackslash
) as described previously.
Another option is 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
):
\usepackage{tabularx}
% ...
\newcolumntype{R}{>{\raggedleft\arraybackslash}X}%
\begin{tabularx}{\textwidth}{ |l|R|l|R| }
\hline
label 1 & label 2 & label 3 & label 4 \\
\hline
item 1 & item 2 & item 3 & item 4 \\
\hline
\end{tabularx} |
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:
\usepackage{tabularx}
% ...
\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| }
\hline
Label 1 & \multicolumn{2}{>{\centering\setlength\hsize{2\hsize} }X|}{Label 2} & Label 3\tabularnewline
\hline
123 & 123 & 456 & 123 \tabularnewline
\hline
123 & 123 & 456 & 123 \tabularnewline
\hline
\end{tabularx} |
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{tabularx}
\usepackage[table]{xcolor} %Used to color the last column
% ...
\newcolumntype{L}[1]{>{\hsize=#1\hsize\raggedright\arraybackslash}X}%
\newcolumntype{R}[1]{>{\hsize=#1\hsize\raggedleft\arraybackslash}X}%
\newcolumntype{C}[2]{>{\hsize=#1\hsize\columncolor{#2}\centering\arraybackslash}X}%
\begin{tabularx}{\textwidth}{ | L{1} | R{0.5} | R{0.5} | C{2}{gray} | }
\hline
label 1 & label 2 & label 3 & label 4 \\
\hline
item 1 & item 2 & item 3 & item 4 \\
\hline
\end{tabularx} |
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 | edit source]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.
\usepackage{tabulary}
...
\begin{center}
\begin{tabulary}{0.7\textwidth}{LCL}
Short sentences & \# & Long sentences \\
\hline
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. \\
\end{tabulary}
\end{center} |
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 | edit source]It works pretty much like tabularx.
Note: tabu is currently broken and unmaintained
\begin{tabu} to \linewidth {llX[2]lllXl}
% ...
\end{tabu} |
to \linewidth
specifies the target width.
The X parameter can have an optional span factor.
Table across several pages
[edit | edit source]Long tables are natively supported by LaTeX thanks to the longtable environment, which replaces both the tabular and table environments or rather combines them into a single environment. Unfortunately, this environment does not support stretching (X columns).
The tabu package (which is no longer maintained) 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
\endhead
\\ \hline
\multicolumn{5}{r}{There is more to come} \\
\endfoot
\\ \hline
\endlastfoot
% 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 | edit source]Adding a partial vertical line to an individual cell:
\begin{tabular}{ l c r }
\hline
1 & 2 & 3 \\ \hline
4 & 5 & \multicolumn{1}{r|}{6} \\ \hline
7 & 8 & 9 \\ \hline
\end{tabular} |
Removing part of a vertical line in a particular cell:
\begin{tabular}{ | l | c | r | }
\hline
1 & 2 & 3 \\ \hline
4 & 5 & \multicolumn{1}{r}{6} \\ \hline
7 & 8 & 9 \\ \hline
\end{tabular} |
Vertically centered images
[edit | edit source]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 | edit source]The tabular environment does not handle footnotes properly. The longtable fixes that.
Professional tables
[edit | edit source]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 | edit source]
\begin{tabular}{lllllr}
\hline
\multicolumn{5}{c}{Item} \\
\cline{1-5}
Animal & Description & Price (\$) \\
\hline
Gnat & per gram & 13.65 \\
& each & 0.01 \\
Gnu & stuffed & 92.50 \\
Emu & stuffed & 33.33 \\
Armadillo & frozen & 8.99 \\
\hline
\end{tabular} |
Using array
[edit | edit source]
\usepackage{array}
%or \usepackage{dcolumn}
...
\begin{tabular}{llr}
\firsthline
\multicolumn{2}{c}{Item} \\
\cline{1-2}
Animal & Description & Price (\$) \\
\hline
Gnat & per gram & 13.65 \\
& each & 0.01 \\
Gnu & stuffed & 92.50 \\
Emu & stuffed & 33.33 \\
Armadillo & frozen & 8.99 \\
\lasthline
\end{tabular} |
Using booktabs
[edit | edit source]
\usepackage{booktabs}
\begin{tabular}{llr}
\toprule
\multicolumn{2}{c}{Item} \\
\cmidrule(r){1-2}
Animal & Description & Price (\$) & 2\\
\midrule
Gnu & stuffed & 92.50 & 2 \\
Emu & stuffed & 33.33 & 2 \\
Armadillo & frozen & 8.99 & 2 \\
\bottomrule
\end{tabular} |
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 | edit source]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 | edit source]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{table}
\begin{tabular}{| r | r || c | c | c |}
...
\end{tabular}
\caption{A normal caption}
\caption*{
A legend, even a table can be used
\begin{tabular}{l l}
item 1 & explanation 1 \\
\end{tabular}
}
\end{table} |
The normal caption is needed for labels and references.
The eqparbox package
[edit | edit source]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 \eqmakebox
es 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:comand
\newsavebox{\tstretchbox}
\newcolumntype{S}[1]{%
>{\begin{lrbox}{\tstretchbox} }%
l%
<{\end{lrbox}%
\eqmakebox[#1][s]{\unhcopy\tstretchbox} }%
} |
See the documentation of the eqparbox package for more details.
The paracol package
[edit | edit source]The various tabular environments available for LaTeX are feature rich; however, they lack the ability to automatically page break large rows. The paracol package provides automatic page breaks in between rows and in certain cases can replace the tabular environment. Such situations could be common in documents that require translations and definitions, which may also includes lists.
For further detail see the documentation of the paracol package.
Floating with table
[edit | edit source]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.
Please understand: you do not have to use floating tables. If you want to place your tables where they lie in your source code and you do not need any label, do not use table at all! This is a very common misunderstanding among newcomers. |
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]
\centering
\begin{tabular}{|l|}
... your table ...
\end{tabular}
\caption{This table shows some data}
\label{tab:myfirsttable}
\end{table} |
In the table, we used a label, so now we can refer to it just like any other reference:
\ref{tab:myfirsttable} |
The table environment is also useful when you want to have a list of tables at the beginning or end of your document with the command
\listoftables |
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 | edit source]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:
- calc2latex: for LibreOffice and OpenOffice.org Calc spreadsheets,
- excel2latex: for Microsoft Office Excel,
- matrix2latex: for Python and MATLAB,
- pandas: pandas DataFrame's have a method to convert data they contain to latex,
- latex-tools: a Ruby library,
- xtable: a library for R,
- org-mode: for Emacs users, org-mode tables can be used inline in LaTeX documents, see [11] for a tutorial.
- Emacs align commands: the align commands can clean up a messy LaTeX table.
- Online Table generator for LATeX: An online tool for creating simple tables within the browser. LaTeX format is directly generated as you type.
- Create LaTeX tables online : Online tool.
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 spreadsheet 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 features?
[edit | edit source]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, e.g. by importing the data directly from .csv (comma-separated value) files instead of manually writing the whole tables in LaTeX code. Programs such as Excel, LibreOffice Calc etc. can export data sheets as .csv files.
References
[edit | edit source]- ↑ D Carlisle. "Decimals in table don't align with dcolumn when bolded". Stackexchange.
- ↑ Package multirow on CTAN
Title creation
[edit | edit source]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 | edit source]Most document classes provide a simple interface to store details to be represented in the title and to typeset the actual title. The standard classes provide just four storing commands (\title
, \author
\thanks
and \date
). You can store any information you want to be shown in the title, including formatting.
The actual title will be typeset by issuing the command \maketitle
. The layout is defined by the documentclass in use.
\documentclass{article}% use option titlepage to get the title on a page of its own.
\usepackage{blindtext}
\title{The Triangulation of Titling Data in Non-Linear Gaussian Fashion via $\rho$ Series\thanks{No procrastination}}
\date{2017\\ December}
\author{John Doe\\ Magic Department\thanks{I am no longer a member of this department}, Richard Miles University
\and Richard Row, \LaTeX\ Academy}
\begin{document}
\maketitle
\section{Introduction}
\blindtext
\end{document} |
The command \thanks
will store content, which will produce a footnote along with the title. As the name suggests, it can be used to thank someone. Or just to print an email address or similar in a footnote.
The authors are separated by the command \and
, allowing author blocks to be output next to each other. In the example above, there is not enough horizontal space to fit both authors on the same line.
If \date
was not defined, LaTeX will print the current date. If you want to omit the date completely, use \date{}
, which stores an empty string.
The commands to store your title data can be used in the preamble. Since \maketitle
does actual output, it needs to be used after \begin{document}
. Usually, the title is the first thing in a document.
Please see examples for KOMA-script and memoir
classes below. Both provide (different) commands to change the appearance of the title. Learn later how to completely design your own titlepage.
\documentclass{scrbook}
\setkomafont{author}{\scshape}
\usepackage{blindtext}
\title{How hard would it be to build a spaceship from scrap}
\author{Carl Capybara\thanks{I never procrastinate} \and Walter Wombat}
\subtitle{A closer look at the expenses}
\subject{a funny paper}
\begin{document}
\maketitle
\addchap{Introduction}
\blindtext
\end{document} |
\documentclass{memoir}% use option titlepage to get the title on a page of its own.
\usepackage{blindtext}
\title{The influence of colour on the floating velocity of rubber ducks}
\author{Peter Piranha}
\renewcommand{\maketitlehookb}{\centering You won't expect the results}
\begin{document}
\maketitle
\chapter{Introduction}
\blindtext
\end{document} |
As usual, the class documentation reveals more details about the possible commands.
The title for journal submission
[edit | edit source]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 | edit source]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:
- Alignment
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.
- Images
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 | edit source]All these tips might have made you confused. Here is a practical and compliable example. The picture in use comes with package mwe
and should be available with every complete LaTeX installation. You can start testing right away.
\documentclass[12pt,a4paper]{report}
\usepackage{mwe}
\begin{document}
\begin{titlepage}
\centering
\includegraphics[width=0.15\textwidth]{example-image-1x1}\par\vspace{1cm}
{\LARGE \textsc{Columbidae University}\par}
\vspace{1cm}
{\Large \textsc{Final year project}\par}
\vspace{1.5cm}
{\huge\bfseries Pigeons love doves\par}
\vspace{2cm}
{\Large\itshape John Birdwatch\par}
\vfill
supervised by\par
Dr.~Mark \textsc{Brown}
\vfill
% Bottom of the page
{\large \today\par}
\end{titlepage}
\end{document} |
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 | edit source]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 needs 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.
\documentclass{report}
\usepackage{pdfpages}
\begin{document}
\includepdf{reportTitlepage2016}
\tableofcontents
\chapter{Introducing birds}
\end{document} |
A title to be re-used multiple times
[edit | edit source]Some universities, departments and companies have strict rules how a title page of a report should look. To ensure the very same output for all reports, a redefinition 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]
\RequirePackage{graphicx}
\newcommand*{\project}[1]{\gdef\@project{#1}%
}
\newcommand*{\@project}{Final Year Project}
\newcommand*{\supervisor}[1]{\gdef\@supervisor{#1}%
}
\newcommand*{\@supervisor}{\texttt{\string\supervisor} currently
not set. Please fix this.}
\renewcommand*{\maketitle}{%
\begin{titlepage}
{\raggedleft%
\includegraphics[width=3cm]{example-image-16x9}\par
}\vspace{1cm}
\centering
{\scshape\LARGE Columbidae University \par}
\vspace{1cm}
{\scshape\Large\@project\unskip\strut\par}
\vspace{1.5cm}
{\huge\bfseries\@title\unskip\strut\par}
\vspace{2cm}
{\Large\itshape\@author\unskip\strut\par}
\vfill
supervised by\par
\@supervisor\unskip\strut\par
\vfill
{\large \@date\par}
\end{titlepage}
}
\endinput |
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.
\documentclass{book}
\usepackage{columbidaeTitle}
%\supervisor{Dr. James Miller}
\project{Bachelor Thesis}
\author{A LaTeX enthusiast}
\title{Why I want to be a duck}
\begin{document}
\maketitle
\tableofcontents
\chapter{Ducks are awesome}
\end{document} |
Packages for custom titles
[edit | edit source]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 Italy.
Package authblk [3] provides new means to typeset the authors. This is especially helpful for journal submissions without an available template.
More titlepage examples
[edit | edit source]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 | edit source]Page Layout
[edit | edit source]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 | edit source]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 | edit source]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.
- one inch +
\hoffset
- one inch +
\voffset
\oddsidemargin
= 31pt\topmargin
= 20pt\headheight
= 12pt\headsep
= 25pt\textheight
= 592pt\textwidth
= 390pt\marginparsep
= 10pt\marginparwidth
= 35pt\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
\usepackage{showframe}
to the document.
Page size
[edit | edit source]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:
\documentclass[a4paper]{article} |
Note that the standard LaTeX classes use US Letter by default regardless of your TeX distribution configuration. If you have TeX Live configured to use A4 paper, it will be the default only for plainTeX and classes not specifying the paper dimension. |
The a4paper option with the article document class by itself has no effect. It will only affect the page size in connection with some appropriate package, like the geometry package or the hyperref package. |
More size options with geometry
[edit | edit source]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:
\usepackage[a4paper]{geometry} |
The geometry package has many pre-defined page sizes, like a4paper, built in. Others include:
- a0paper, a1paper, ..., a6paper,
- b0paper, b1paper, ..., b6paper,
- letterpaper,
- legalpaper,
- executivepaper.
To explicitly change the paper dimensions using the geometry package, the paperwidth and paperheight options can be used. For example:
\usepackage[paperwidth=5.5in, paperheight=8.5in]{geometry} |
Package provides many flexibility on setting the page layout, including specifying specific layout of each page using the:
\newgeometry{
key=val // package options
}
\restoregeometry
While very flexible, this package also comes with limitations. For instance, page size cannot be provided to individual pages, which requires different approaches for the workaround.
Page size issues
[edit | edit source]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 myfile.ps # DVI → PS ps2pdf myfile.ps 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
\documentclass[...,a4paper,...]{...}
\special{papersize=210mm,297mm} |
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 | edit source]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.
Margins
[edit | edit source]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 with the 10pt default font size (and about 90 if the 12pt documentclass option is used):
\usepackage{fullpage} |
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:
\usepackage[cm]{fullpage} |
- 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
\usepackage[margin=1in]{geometry} |
You can combine the margin options with the page size options seen in this paragraph.
- If the page size is A4, you can use the layaureo package. The big option further narrows the margins.
- 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:
\usepackage[a4paper,includeheadfoot,margin=2.54cm]{geometry} |
- Edit individual page dimension variables described above, using the
\addtolength
and\setlength
commands. See the Lengths chapter. For instance,
\setlength{\textwidth}{6.5in}
\addtolength{\voffset}{-5pt} |
Odd and even margins
[edit | edit source]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.
\documentclass[twoside]{report}
\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:
\setlength{\oddsidemargin}{15.5pt}
\setlength{\evensidemargin}{15.5pt} |
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 | edit source]The top margin above a chapter can be changed using the titlesec package. Example: [12]
\usepackage{titlesec}
\titlespacing*{\chapter}{0pt}{-50pt}{20pt}
\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 | edit source]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 | edit source]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:
\usepackage[landscape]{geometry} |
Although, if you intend to use geometry to set your paper size, don't add the \usepackage
commands twice, simply string all the options together, separating with a comma:
\usepackage[a4paper,landscape]{geometry} |
Using standard LaTeX classes, you can use the same class options:
\documentclass[a4paper,landscape]{article} |
Change orientation of specific part
[edit | edit source]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:
\usepackage{pdflscape}
% ...
\begin{landscape}
\begin{table}
\centering % optional, probably makes it look better to have it centered on the page
\begin{tabular}{....}
% ...
\end{tabular}
\end{table}
\end{landscape} |
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 | edit source]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 | edit source]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.
\usepackage{geometry}
\usepackage{pdflscape}
% ...
\newgeometry{margin=1cm}
\begin{landscape}
\thispagestyle{empty} %% Remove header and footer.
\begin{table}
\begin{center}
\footnotesize %% Smaller font size.
\begin{tabular}{....}
% ...
\end{tabular}
\end{center}
\end{table}
\end{landscape}
\restoregeometry |
Note that order matters!
Page background
[edit | edit source]There are many ways on implementing background for a page. Below is most common packages used:
- eso-pic package will let you print content in the background of every page or individual pages.
\usepackage{tikz} % for \gradientbox below.
\usepackage{eso-pic}
\newcommand{\gradientbox}[3]{%
\begin{tikzpicture}
\node[left color=#1,right color=#2] {#3};
\end{tikzpicture}%
}
\AddToShipoutPicture*{%
\AtPageLowerLeft{%
\rotatebox{90}{
\gradientbox{blue!20}{white}{%
\begin{minipage}{\paperheight}%
\hspace*{ \stretch{1} }\textcopyright~2013 \makeatletter\@author\makeatother.\hspace*{ \stretch{1} }
\end{minipage}%
}
}%
}%
} |
The starred-version of the \AddToShipoutPicture
command applies to the current page only.
- background package let users include watermarks and pictures in the background.
\usepackage{background}
\backgroundsetup{
opacity = 0.5,
angle = 0,
contents = {\includegraphics{example.pdf} } |
Multi-column pages
[edit | edit source]Using the twocolumn optional class argument
[edit | edit source]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.
- Use multicols* environment for unbalanced columns, whereby each column is completely filled before starting with the next column.
- Vertical rules between columns can be customised.
- Column environments can be easily customised locally or globally.
Using multicol package
[edit | edit source]The multicol package overcomes some of the shortcomings of twocolumn and provides the multicol
environment. To create a typical two-column layout:
\begin{multicols}{2}
lots of text
\end{multicols} |
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 | edit source]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 | edit source]In professional books, it's not desirable to have single lines at the beginning or end of a page. In typesetting such situations are called 'widows' and 'orphans'. Normally it is possible that widows and orphans appear in LaTeX documents. You can try to deal with them using manual page formatting, but there's also an automatic solution.
LaTeX has a parameter for 'penalty' for widows and orphans ('club lines' in LaTeX terminology). With the greater penalty LaTeX will try more to avoid widows and orphans. You can try to increase these penalties by putting following commands in your document preamble:
\widowpenalty=300
\clubpenalty=300 |
If this does not help, you can try increasing these values even more, to 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.
\needspace{5\baselineskip}
Some
text
on
5
lines. |
Troubleshooting / Debugging
[edit | edit source]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.
\usepackage[showframe]{geometry} |
Examining the log of tex could be helpful as well - it should provide many useful information. In addition, following packages can help on visual debugging layout:
%\usepackage{layout}
%\usepackage{showframe}
% \layout % - place it inside "document" section to see the layout where you need it more conveniently |
Which will print layout and frames. The statements could be on top of the source file and uncommented when required.
Notes and References
[edit | edit source]This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.
Importing Graphics
[edit | edit source]Importing external graphics
[edit | edit source]You can import external graphics using package
graphicx
. The most important command is
\includegraphics
. LaTeX itself treats the image like
normal text, i.e. as a box of certain height and width.
\documentclass{article}
\usepackage{graphicx}
\begin{document}
The following image does not show any wombats
\includegraphics[height=\baselineskip]{example-image}.
\includegraphics[height=3cm]{example-image-a}\includegraphics[width=5cm]{example-image-b}
\includegraphics[height=3cm]{example-image-a} \includegraphics[width=5cm]{example-image-b}
\end{document}
The package documentation list the options width
and
height
, as well as others.
Using pdflatex
several graphics formats are
supported: pdf
, png
and
jpg
. Modern installations of LaTeX can use
eps
files as well, but indirectly.
LaTeX in dvi
-mode supports only
eps
-files.
You can align the images in a matrix. You just have to think of a proper width for the images.
\documentclass{article}
\usepackage{graphicx}
\usepackage{blindtext}
\usepackage{showframe}
\begin{document}
\begin{center}
\includegraphics[width=.3\linewidth]{example-image}\quad\includegraphics[width=.3\linewidth]{example-image-a}\quad\includegraphics[width=.3\linewidth]{example-image-b}
\\[\baselineskip]% adds vertical line spacing
\includegraphics[width=.3\linewidth]{example-image}\quad\includegraphics[width=.3\linewidth]{example-image-a}\quad\includegraphics[width=.3\linewidth]{example-image-b}
\end{center}
\end{document}
Three images in one line, each image has a width of just 30 % of the available line width, centered with respect to the text below.
If you want to add a caption and let LaTeX keep track of the numbering, have a look at the floats section.
Converting graphics
[edit | edit source]- Note
You should also take a look at Export To Other Formats for other possibilities.
- epstopdf
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 a whole page with your small graphics somewhere on it, use
$ epstopdf --gsopt=-dEPSCrop foo.eps
or try using the ps2pdf utility which should be installed with Ghostscript (required for any TeX distribution).
$ ps2pdf -dEPSCrop foo.eps
to crop the final PDF.
- eps2eps
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
imgtops is a lightweight graphics utility for conversions between raster graphics (JPG, PNG, ...) and EPS/PS files.
- Inkscape
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.
- pstoedit
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).
- PDFCreator
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
- Sam2p (convert) or
- ImageMagick (convert) or
- GraphicsMagick (gm convert).
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 | edit source]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 | edit source]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 | edit source]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 | edit source]- Dia
Dia is a cross platform diagramming utility which can export eps images, or generate tex drawn using the tikz package.
- Inkscape
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).
- Ipe
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.
- lpic
Yet another solution is provided by the lpic packages [14], which allows TeX annotations to imported graphics. See Labels in the figures.
- LibreOffice
It is also possible to export vector graphics to EPS format using LibreOffice Draw, which is an open source office suite available for Windows, Linux and Mac.
- TpX
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
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. 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:
- Create the drawing in xfig. Wherever you need LaTeX text, such as a mathematical formula, enter a LaTeX string in a textbox.
- 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.
- 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.
- In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image:
\begin{figure} \centering \input{test.pdf_t} \caption{Your figure} \label{figure:example} \end{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.
- Make sure to include packages graphicx and color in the file, with the
\usepackage
command right below the\documentclass
command, like this:\usepackage{graphicx} \usepackage{color}
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 | edit source]- Adobe Photoshop
Photoshop can save to EPS.
- GIMP
GIMP, has a graphical user interface, and it is multi-platform. It can save to EPS and PDF.
Plots and Charts
[edit | edit source]- Generic Mapping Tools (GMT)
Generic Mapping Tools (GMT), maps and a wide range of highly customisable plots.
- Gnumeric
Gnumeric, spreadsheets has SVG, EPS, PDF export
- Gnuplot
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
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
R, statistical and scientific figures.
Editing EPS graphics
[edit | edit source]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 | edit source]- ↑ Johan B. C. Engelen. "How to include an SVG image in LATEX" (PDF). mirrorcatalogs.com.
- ↑ Philip Ilten. "The svg package on CTAN". ctan.org.
Floats, Figures and Captions
[edit | edit source]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 arrange pictures as well. This is where floats come into play.
Floats
[edit | edit source]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 unprocessed (placed) floats in line. LaTeX by default can cope with maximum 18 floats and a symptomatic error is:
! LaTeX Error: Too many unprocessed floats.
The morefloats package lifts this limit.
Figures
[edit | edit source]To create a figure that floats, use the figure environment.
\begin{figure}[placement specifier]
... figure contents ...
\end{figure} |
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} .
|
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. See the New commands section for more information on this.
Figures with borders
[edit | edit source]It's possible to get a thin border around all figures. You have to write the following once at the beginning of the document:
\usepackage{float}
\floatstyle{boxed}
\restylefloat{figure} |
The border will not include the caption.
Tables
[edit | edit source]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:
\begin{table}
\begin{tabular}{...}
... table data ...
\end{tabular}
\end{table} |
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 | edit source]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.
Captions
[edit | edit source]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:
\documentclass[a4paper,12pt]{article}
\usepackage[english]{babel}
\usepackage{graphicx}
\begin{document}
\begin{figure}
\caption{A picture of a gull.}
\centering
\includegraphics[width=0.5\textwidth]{gull}
\end{figure}
\begin{figure}
\centering
\reflectbox{%
\includegraphics[width=0.5\textwidth]{gull}}
\caption{A picture of the same gull
looking the other way!}
\end{figure}
\begin{table}
\centering
\begin{tabular}{| l c r |}
\hline
1 & 2 & 3 \\
4 & 5 & 6 \\
7 & 8 & 9 \\
\hline
\end{tabular}
\caption{A simple table}
\end{table}
Notice how the tables and figures
have independent counters.
\end{document} |
Note that the command \reflectbox{...}
flips its content horizontally.
Side captions
[edit | edit source]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.
\documentclass{article}
\usepackage{graphicx}
\usepackage{sidecap}
\begin{document}
\begin{SCfigure}
\centering
\caption{ ... caption text ... }
\includegraphics[width=0.3\textwidth]%
{Giraffe_picture}% picture filename
\end{SCfigure}
\end{document} |
Note that if you define your own float placement (default is tbp) with one of the sidecap package environments, you need to provide additional relwidth argument like this: \begin{SCfigure}[1][!h] . |
Unnumbered captions
[edit | edit source]In some types of documents (such as presentations), it may not be desirable for figure captions to start with 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.
Caption Setup Rename
[edit | edit source]In case you want to rename your table caption from "Table" to something else, you can use the \captionsetup
command. For example,
\usepackage{caption}
\captionsetup[table]{name=New Table Name} |
\usepackage{caption} \captionsetup[table] {name=New Table Name}
Lists of figures and tables
[edit | edit source]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:
\documentclass[12pt,]{article}
\usepackage{graphicx}
\newcommand{\species}[1]{\textit{#1} sp.}
\begin{document}
\listoffigures
\section{Introduction}
\begin{figure}
\centering
\includegraphics[width=4in]{gecko}
\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.}
\end{figure}
\end{document} |
Labels and cross-referencing
[edit | edit source]Labels and cross-references work fairly similarly to the general case - see the Labels and Cross-referencing section for more information.
If you want to label a figure so that you can reference it later, you have to add the label after the caption (inside seems to work in LaTeX 2e) but inside the floating environment. If it is declared outside, it will give the section number. |
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 | edit source]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 work 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:
\usepackage{wrapfig} |
This then gives you access to:
\begin{wrapfigure}[lineheight]{position}[overhang]{width} |
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:
\begin{wrapfigure}{r}{0.5\textwidth}
\begin{center}
\includegraphics[width=0.48\textwidth]{gull}
\end{center}
\caption{A gull}
\end{wrapfigure} |
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 | edit source]You can use intextsep
parameter to control additional space above and below the figure: \setlength\intextsep{0pt}
To control the horizontal space between the image and the text, use the columnsep
parameter.
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 the 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 cases, we just added some negative vertical spaces to shrink everything up:
\begin{wrapfigure}{r}{0.5\textwidth}
\vspace{-20pt}
\begin{center}
\includegraphics[width=0.48\textwidth]{gull}
\end{center}
\vspace{-20pt}
\caption{A gull}
\vspace{-10pt}
\end{wrapfigure} |
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.
Subfloats
[edit | edit source]A useful extension is the subcaption[20] package, which uses subfloats within a single float. The subfig package (subfigure package is deprecated[5]) is a useful alternative 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:
\usepackage{graphicx}
\usepackage{subcaption}
\begin{figure}
\centering
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{gull}
\caption{A gull}
\label{fig:gull}
\end{subfigure}
~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc.
%(or a blank line to force the subfigure onto a new line)
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{tiger}
\caption{A tiger}
\label{fig:tiger}
\end{subfigure}
~ %add desired spacing between images, e. g. ~, \quad, \qquad, \hfill etc.
%(or a blank line to force the subfigure onto a new line)
\begin{subfigure}[b]{0.3\textwidth}
\includegraphics[width=\textwidth]{mouse}
\caption{A mouse}
\label{fig:mouse}
\end{subfigure}
\caption{Pictures of animals}\label{fig:animals}
\end{figure} |
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>}
\centering
... table 1 ...
\caption{<sub caption>}
\end{subtable}
~
\begin{subtable}[<placement specifier>]{<width>}
\centering
... table 2 ...
\caption{<sub caption>}
\end{subtable}
\end{table} |
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
Figures in multiple parts
[edit | edit source]Sometimes you need to divide up a figure over multiple floats, for instance because the figure is too big to fit on one page. In this case you can use continued figures using the caption
package.
Put this in your preamble:
\usepackage{caption}
\DeclareCaptionLabelFormat{cont}{#1~#2\alph{ContinuedFloat}}
\captionsetup[ContinuedFloat]{labelformat=cont} |
Then you can use continued floats as follows.
\begin{figure}
\ContinuedFloat*
\[ e^{i \pi} + 1 = 0 \]
\caption{Euler's identity, first form.}
\end{figure}
\begin{figure}
\ContinuedFloat
\[ e^{i \pi} = -1 \]
\caption{Euler's identity, second form.}
\end{figure} |
Wide figures in two-column documents
[edit | edit source]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.
Custom floats
[edit | edit source]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.
- Add
\usepackage{float}
to the preamble of your document - 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'.
- The default name that appears at the start of the caption is the type. If you wish to alter this, use
\floatname{type}{floatname}
- Changing float style can be issued with
\floatstyle{style}
(Works on all subsequent\newfloat
commands, therefore, must be inserted before\newfloat
to be effective).- plain - the normal style for LaTeX floats, but the caption is always below the content.
- plaintop - the normal style for LaTeX floats, but the caption is always above the content.
- boxed - a box is drawn that surrounds the float, and the caption is printed below.
- ruled - the caption appears above the float, with rules immediately above and below. Then the float contents, followed by a final horizontal rule.
Float styles can also be customized as the second example below illustrates.
An example document using a new program float type:
\documentclass{article}
\usepackage{float}
\floatstyle{ruled}
\newfloat{program}{thp}{lop}
\floatname{program}{Program}
\begin{document}
\begin{program}
\begin{verbatim}
class HelloWorldApp {
public static void main(String[] args) {
//Display the string
System.out.println("Hello World!");
}
}
\end{verbatim}
\caption{The Hello World! program in Java.}
\end{program}
\end{document} |
The verbatim is an environment already discussed in Special paragraphs. It is good for source code, but if you want to introduce a lot of code you might consider using the listings package described in Source Code Listings, that was made just for it.
While this is useful, one should be careful when embedding the float within another float. In particular, the error
not in outer par mode
may occur. One solution might be to use the [H] option (not any other) on the inner float, as this option "pins" the inner float to the outer one.
Newly created floats with \newfloat
can also be used in combination with the wrapfig package from above. E.g. the following code creates a floating text box, which floats in the text on the right side of the page and is complete with caption, numbering, an index file with the extension .lob and a customization of the float's visual layout:
\documentclass{article}
% have hyperref package before float in order to get strange errors with .\theHfloatbox
\usepackage{hyperref}
\usepackage{float}
% allows use of "@" in control sequence names
\makeatletter
% this creates a custom and simpler ruled box style
\newcommand\floatc@simplerule[2]{{\@fs@cfont #1 #2}\par}
\newcommand\fs@simplerule{\def\@fs@cfont{\bfseries}\let\@fs@capt\floatc@simplerule
\def\@fs@pre{\hrule height.8pt depth0pt \kern4pt}%
\def\@fs@post{\kern4pt\hrule height.8pt depth0pt \kern4pt \relax}%
\def\@fs@mid{\kern8pt}%
\let\@fs@iftopcapt\iftrue}
% this code block defines the new and custom floatbox float environment
\floatstyle{simplerule}
\newfloat{floatbox}{thp}{lob}[section]
\floatname{floatbox}{Text Box}
\begin{document}
\begin{floatbox}{r}{}
\textit{Bootstrapping} is a resampling technique used
for robustly estimating statistical quantities, such as
the model fit $R^2$. It offers some protection against
the sampling bias.
\caption{Bootstrapping}
\end{floatbox}
\end{document} |
Caption styles
[edit | edit source]To change the appearance of captions, use the caption [21] package. For example, to make all caption labels small and bold:
\usepackage[font=small,labelfont=bf]{caption} |
The KOMA script packages [22] have their own caption customizing features with e.g. \captionabove
, \captionformat
and \setcapwidth
. However these definitions have limited effect on newly created float environments with the wrapfig package.
Alternatively, you can redefine the \thefigure
command:
\renewcommand{\thefigure}{\arabic{section}.\arabic{figure}} |
See this page for more information on counters. Finally, note that the caption2 package has long been deprecated.
Labels in the figures
[edit | edit source]There is a LaTeX package lpic [23] to put LaTeX on top of included graphics, thus allowing to add TeX annotations to imported graphics. It defines a convenient interface to put TeX over included graphics, and allows for drawing a white background under the typeset material to overshadow the graphics. It is a better alternative for labels inside of graphics; you do not have to change text size when rescaling pictures, and all LaTeX power is available for labels.
A very similar package, with somewhat different syntax, is pinlabel [24]. The link given also points to the packages psfrag and overpic.
A much more complicated package which can be used in the same way is TikZ. TikZ is a front-end to a drawing library called pgf (which is used to make beamer for instance). It can be used to label figures by adding text nodes on top of an image node.
Summary
[edit | edit source]That concludes all the fundamentals of floats. You will hopefully see how much easier it is to let LaTeX do all the hard work and tweak the page layouts in order to get your figures in the best place. As always, the fact that LaTeX takes care of all caption and reference numbering is a great time saver.
Notes and references
[edit | edit source]- ↑ http://www.ctan.org/tex-archive/macros/latex/contrib/float/
- ↑ Float environment positioning, by Frank Mittelbach
- ↑ http://tex.stackexchange.com/questions/28556/how-to-place-a-float-at-the-top-of-a-floats-only-page
- ↑ http://ftp.univie.ac.at/packages/tex/macros/latex/contrib/wrapfig/wrapfig-doc.pdf
- ↑ http://ctan.org/pkg/subfigure
This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.
Footnotes and Margin Notes
[edit | edit source]Footnotes
[edit | edit source]Footnotes are a very useful way of providing extra information to the reader. Usually, it is non-essential information which can be placed at the bottom of the page. This keeps the main body of text concise.
The footnote facility is easy to use. The command you need is: \footnote{text}
. Do not leave a space between the command and the word where you wish the footnote marker to appear, otherwise LaTeX will process that space and will leave the output not looking as intended.
Creating a footnote is easy.\footnote{An example footnote.} |
LaTeX will obviously take care of typesetting the footnote at the bottom of the page. Each footnote is numbered sequentially - a process that, as you should have guessed by now, is automatically done for you.
If you want your footnote to be at the bottom of the page (instead of the default position of `glued` under the text), consider using:
\usepackage[bottom]{footmisc} |
You can also choose to place the footnote text manually. In this case we use the \footnotemark
-\footnotetext
duo:
\footnotemark
% ...
Somewhere else\footnotetext{This is my footnote!} |
The footnote number can also be explicitly specified.
\footnotemark[17]
% ...
Somewhere else\footnotetext[17]{This is my footnote!} |
Customization
[edit | edit source]- Enumeration/counter style
It is possible to customize the footnote marking. By default, they are numbered sequentially (Arabic). However, without going too much into the mechanics of LaTeX at this point, it is possible to change this using the following command (which needs to be placed at the beginning of the document, or at least before the first footnote command is issued).
\renewcommand{\thefootnote}{\arabic{footnote}}
|
Arabic numerals, e.g., 1, 2, 3... |
\renewcommand{\thefootnote}{\roman{footnote}}
|
Roman numerals (lowercase), e.g., i, ii, iii... |
\renewcommand{\thefootnote}{\Roman{footnote}}
|
Roman numerals (uppercase), e.g., I, II, III... |
\renewcommand{\thefootnote}{\alph{footnote}}
|
Alphabetic (lowercase), e.g., a, b, c... |
\renewcommand{\thefootnote}{\Alph{footnote}}
|
Alphabetic (uppercase), e.g., A, B, C... |
\renewcommand{\thefootnote}{\fnsymbol{footnote}}
|
A sequence of nine symbols, try it and see! |
To make a footnote without number mark use this declaration:
\let\thefootnote\relax\footnote{There is no number in this footnote} |
In this way, the numbering is switched off globally. To have only one footnote without number mark, the above command has to be placed inside { }. Nevertheless, in that case, the current footnote counter is still incremented, so for instance you'd get footnote 1, unnumbered, and 3. A better solution[1] consists in defining the following macro in the preamble, and to use it:
\makeatletter
\def\blfootnote{\xdef\@thefnmark{}\@footnotetext}
\makeatother |
The package footmisc offers many possibilities for customizing the appearance of footnotes. It can be used, for example, to use a different font within footnotes.
Reset counter
[edit | edit source]- every section
\makeatletter
\@addtoreset{footnote}{section}
\makeatother |
- every page
(This may require running LaTeX twice)
\usepackage{perpage} %the perpage package
\MakePerPage{footnote} %the perpage package command |
Referencing a footnote
[edit | edit source]Can be done by placing a \label{labelName}
in the end of the footnote and use \ref{labelName}
to refer to the footnote.
Common problems and workarounds
[edit | edit source]- Footnotes don't work with tables, as it is considered a bad practice. You can overcome this limitation with several techniques: you can use
\footnotemark[123]
in the table, and\footnotetext[123]{HelloWorld!}
somewhere on the page. The same with references: use\footnote{HelloWorld!\label{fnote}}
somewhere on the page and\textsuperscript{\ref{fnote}}
in the table. Or, you can add\usepackage{footnotehyper}
and\makesavenoteenv{tabular}
to the preamble, and put your table environment in a\begin{savenotes}
environment. The latter does not work with the packages color or colortbl. See this FAQ page for other approaches (such as the use of tablenotes with threeparttable).
- Footnotes also don't work inside minipage environment. (In fact, several environments break footnote support. The
\makesavenoteenv{environmentname}
command of the footnote package might fix most.) The minipage includes its own footnotes, independent of the document's. The package mpfnmark allows greater flexibility in managing these two sets of footnotes.
- If the text within the footnote is a URL (using
\url
or\href
commands) with special characters, it will not compile. You must either escape the characters with a leading backslash, or use another command.
- If the text within the footnote is very long, LaTeX may split the footnote over several pages. You can prevent LaTeX from doing so by increasing the penalty for such an operation. To do this, insert the following line into the preamble of your document:
\interfootnotelinepenalty=10000 |
or setting \samepage after footnote command:
\footnote{ \samepage text of the footnote follows }
- To make multiple references to the same footnote, you can use the following syntax:
Text that has a footnote\footnote{This is the footnote} looks like this. Later text referring to the same footnote\footnotemark[\value{footnote}] uses the other command. |
If you need hyperref support, use instead:
Text that has a footnote\footnote{This is the footnote}\addtocounter{footnote}{-1}\addtocounter{Hfootnote}{-1} looks like this. Later text referring to the same footnote\footnotemark uses the other command. |
These approaches will not work if there are other footnotes between the first reference and the subsequent "duplicate" references. For more general solutions, see here and here.
- If the footnote is intended to be added to the title of a chapter, a section, or similar, two methods can be used:
- Write
\section[title] {title\footnote{I'm a footnote referred to the section} }
where title is the title of the section. - Use the footmisc package, with package option stable, and simply add the footnote to the section title.
Margin Notes
[edit | edit source]Margin Notes are useful during the editorial process, to exchange comments among authors. To insert a margin note use \marginpar{margin text}
. For one-sided layout (simplex), the text will be placed in the right margin, starting from the line where it is defined. For two-sided layout (duplex), it will be placed in the outside margin and for two-column layout it will be placed in the nearest margin.
To swap the default side, use \reversemarginpar
and margin notes will then be placed on the opposite side, which would be the inside margin for two-sided layout.
If the text of your marginpar depends on which margin it is put in (say it includes an arrow pointing at the text or refers to a direction as in "as seen to the left..."), you can use \marginpar[left text]{right text}
to specify the variants.
To insert a margin note in an area that \marginpar
can't handle, such as footnotes or equation environments, use the package marginnote.
Another option for adding colored margin notes in a fancy way provides the package todonotes by using \todo{todo note}
. It makes use of the package pgf used for designing and drawing with a huge tool database.
The packages mparhack and marginnote can be used if the native \marginpar
command does not meet your needs.
The marginnote and geometry package can set the widths of the margins and marginnotes as follows.
In the preamble, insert
\usepackage{marginnote} |
and use the geometry package with custom sizes:
\usepackage[top=Bcm, bottom=Hcm, outer=Ccm, inner=Acm, heightrounded, marginparwidth=Ecm, marginparsep=Dcm]{geometry} |
where A, B, C, D, E, F, G, H are all numbers in cm (of course other units than cm can be used).
In the main text, employ the marginnote package according to:
\marginnote{typeset text here...}[Fcm] |
Specifically,
- marginparwidth (E) is the width of the margin note,
- marginparsep (D) is the separation between the paragraph and the margin note,
- F is the downwards vertical offset from the first line the margin note was written (negative values of F shift the margin note upwards), and
- the value G = C − (D + E) is the separation between the edge of the margin note and the edge.
The example on the right was typeset by the following:
\documentclass[a4paper,twoside,english]{article}
\usepackage{lmodern}
\renewcommand{\sfdefault}{lmss}
\usepackage[T1]{fontenc}
\makeatletter
\special{papersize=\the\paperwidth,\the\paperheight}
\usepackage{lipsum}
\usepackage{marginnote}
\usepackage[top=1.5cm, bottom=1.5cm, outer=5cm, inner=2cm, heightrounded, marginparwidth=2.5cm, marginparsep=2cm]{geometry}
\makeatother
\usepackage{babel}
\begin{document}
\section{Margin notes}
\marginnote{This is a margin note using the geometry package, set at 0cm vertical offset to the first line it is typeset.}[0cm]
\marginnote{This is a margin note using the geometry package, set at 5cm vertical offset to the first line it is typeset.}[5cm]
\lipsum[1-10]
\end{document} |
Additionally, the minimum vertical gap between margin notes can be adjusted with \marginparpush
, such as with \setlength{\marginparpush}{0pt}
.
Notes and References
[edit | edit source]- ↑ "LaTeX footnotes". Retrieved 2016-01-14.
This page uses material from Andy Roberts' Getting to grips with LaTeX with permission from the author.
Hyperlinks
[edit | edit source]LaTeX enables typesetting of hyperlinks, useful when the resulting format is PDF, and the hyperlinks can be followed. It does so using the package hyperref.
Hyperref
[edit | edit source]The package hyperref[1] provides LaTeX the ability to create hyperlinks within the document. It works with pdflatex and also with standard "latex" used with dvips and ghostscript or dvipdfm to build a PDF file. If you load it, you will have the possibility to include interactive external links and all your internal references will be turned to hyperlinks. The compiler pdflatex makes it possible to create PDF files directly from the LaTeX source, and PDF supports more features than DVI. In particular PDF supports hyperlinks. Moreover, PDF can contain other information about a document such as the title, the author, etc., which can be edited using this same package.
Usage
[edit | edit source]The basic usage with the standard settings is straightforward. Just load the package in the preamble:
\usepackage{hyperref} |
This will automatically turn all your internal references into hyperlinks. It won't affect the way to write your documents: just keep on using the standard \label
-\ref
system (discussed in the chapter on Labels and Cross-referencing); with hyperref those "connections" will become links and you will be able to click on them to be redirected to the right page. Moreover the table of contents, list of figures/tables and index will be made of hyperlinks, too. The hyperlinks will not show up if you are working in draft mode.
Commands
[edit | edit source]The package provides some useful commands for inserting links pointing outside the document.
\hyperref
[edit | edit source]Usage:
\hyperref[label_name]{''link text''} |
This will have the same effect as \ref{label_name}
but will make the text link text a full link, instead. The two can be combined. If the lemma labelled as mainlemma was number 4.1.1 the following example would result in
We use \hyperref[mainlemma]{lemma \ref*{mainlemma} }. |
We use lemma 4.1.1. |
with the hyperlink as expected. Note the "*" after \ref
for avoiding nested hyperlinks.
\url
[edit | edit source]Usage:
\url{<my_url>} |
It will show the URL using a mono-spaced font and, if you click on it, your browser will be opened pointing at it.
\href
[edit | edit source]Usage:
\href{<my_url>}{<description>} |
It will show the string description using standard document font but, if you click on it, your browser will be opened pointing at my_url. Here is an example:
\url{https://www.wikibooks.org}
\href{https://www.wikibooks.org}{Wikibooks home} |
Both point at the same page, but in the first case the URL will be shown, while in the second case the URL will be hidden. Note that, if you print your document, the link stored using \href
will not be shown anywhere in the document.
Other possibilities
[edit | edit source]Apart from linking to websites discussed above, hyperref can be used to provide mailto links, links to local files, and links to anywhere within the PDF output file.
E-mail address
[edit | edit source]A possible way to insert email links is by
\href{mailto:my_address@wikibooks.org}{my\_address@wikibooks.org} |
It just shows your email address (so people can know it even if the document is printed on paper) but, if the reader clicks on it, (s)he can easily send you an email. Or, to incorporate the url package's formatting and line breaking abilities into the displayed text, use[2]
\href{mailto:my_address@wikibooks.org}{\nolinkurl{my_address@wikibooks.org} } |
When using this form, note that the \nolinkurl
command is fragile and if the hyperlink is inside of a moving argument, it must be preceded by a \protect
command.
Local file
[edit | edit source]Files can also be linked using the url or the href commands. You simply have to add the string run: at the beginning of the link string:
\url{run:/path/to/my/file.ext}
\href{run:/path/to/my/file.ext}{text displayed} |
Following http://tex.stackexchange.com/questions/46488/link-to-local-pdf-file the version with url does not always work, but href does.
It is possible to use relative paths to link documents near the location of your current document; in order to do so, use the standard Unix-like notation (./ is the current directory, ../ is the previous directory, etc.)
Examples:
\href{run:D:/my_folder/my_subfolder/my_file.txt}{Windows, absolute path}
\href{run:my_subfolder/my_file.txt}{Windows, relative path}
\href{run:./my_subfolder/my_file.txt}{Windows, relative path, variant}
\href{run:/my_folder/my_subfolder/my_file.txt}{Linux, absolute path}
\href{run:./my_subfolder/my_file.txt}{Linux, relative path} |
Hyperlink and Hypertarget
[edit | edit source]It is also possible to create an anchor anywhere in the document (with or without caption) and to link to it. To create an anchor, use:
\hypertarget{label}{target caption} |
and to link to it, use:
\hyperlink{label}{link caption} |
where the target caption and link caption are the text that is displayed at the target location and link location respectively.
Note also that if you put a hypertarget, when clicking a link to that hypertarget, it may actually direct to the line after the hypertarget, which is not desirable. Therefore if this occurs, you can report the bug and refer to here for a solution.
Viewing in a browser
[edit | edit source]You can also get an external URL to the hypertarget by appending #label to the URL for the file, or right clicking one of the hyperlinks to the target and copying the URL, or getting the link from the headings in the sidebar of the PDF, or through a process of deduction from viewing (e.g. subsubsection 11.5.1 would have the label subsubsection.11.5.1). This can be useful e.g. for academic and pedagogical purposes. The URL will then direct to the target if you enable a PDF viewer that is compatible with PDF 1.5 in a browser, such as PDF Viewer for Chrome or Chromium browsers, and No PDF Download for Firefox; and on Android the Xodo app works best with links as it renders them with the correct border as with PDF desktop programs, followed by the Foxit PDF app which renders links highlighted in grey (while in other apps links may also work but without any special rendering, such as the Dropbox PDF viewer app; and yet others do not work with links, e.g Drive PDF viewer, PDF reader and Google PDF viewer). You may need to open the URL to the PDF in a new tab, otherwise it may prompt to download it (i.e. if you are clicking on the URL, don't left click, right click and select to open it in a new tab).
Customization
[edit | edit source]The standard settings should be fine for most users, but if you want to change something, that is also possible. There are several variables and two methods to pass those to the package. Options can be passed as an argument of the package when it is loaded (the standard way packages work), or the \hypersetup
command can be used as follows:
\hypersetup{<option1> [, ...]} |
you can pass as many options as you want; separate them with a comma. Options have to be in the form:
variable_name=new_value |
exactly the same format has to be used if you pass those options to the package while loading it, like this:
\usepackage[<option1, option2>]{hyperref} |
Here is a list of the possible variables you can change (for the complete list, see the official documentation). The default values are written in an upright font:
Checkout 3.8 Big list at hyperref-manual at tug.org
variable | values | comment |
---|---|---|
bookmarks | =true,false | show or hide the bookmarks bar when displaying the document |
unicode | =false,true | allows to use characters of non-Latin based languages in Acrobat’s bookmarks |
pdfborder | ={RadiusH RadiusV Width [Dash-Pattern]} | set the style of the border around a link. The first two parameters (RadiusH, RadiusV) have no effect in most pdf viewers. Width defines the thickness of the border. Dash-Pattern is a series of numbers separated by space and enclosed by box-brackets. It is an optional parameter to specify the length of each line & gap in the dash pattern. For example, {0 0 0.5 [3 3]} is supposed to draw a square box (no rounded corners) of width 0.5 and a dash pattern with a dash of length 3 followed by a gap of length 3. There is no uniformity in whether/how different pdf viewers render the dash pattern. |
pdftoolbar | =true,false | show or hide Acrobat’s toolbar |
pdfmenubar | =true,false | show or hide Acrobat’s menu |
pdffitwindow | =true,false | resize document window to fit document size |
pdfstartview | ={FitH},{FitV},etc[3]. | fit the width of the page to the window |
pdftitle | ={text} | define the title that gets displayed in the "Document Info" window of Acrobat |
pdfauthor | ={text} | the name of the PDF’s author, it works like the one above |
pdfsubject | ={text} | subject of the document, it works like the one above |
pdfcreator | ={text} | creator of the document, it works like the one above |
pdfproducer | ={text} | producer of the document, it works like the one above |
pdfkeywords | ={text} | list of keywords, separated by commas, example below |
pdfnewwindow | (=true,false) | define if a new PDF window should get opened when a link leads out of the current document. NB: This option is ignored if the link leads to an http/https address. |
pagebackref | (=false,true) | activate back references inside bibliography. Must be specified as part of the \usepackage{} statement. |
colorlinks | (=false,true) | surround the links by color frames (false) or colors the text of the links (true). The color of these links can be configured using the following options (default colors are shown): |
hidelinks | hide links (removing color and border) | |
linkcolor | =red | color of internal links (sections, pages, etc.) |
linktoc | =none,section,page,all | defines which part of an entry in the table of contents is made into a link |
citecolor | =green | color of citation links (bibliography) |
filecolor | =cyan | color of file links |
urlcolor | =magenta | color of URL links (mail, web) |
linkbordercolor | ={1 0 0} | color of frame around internal links (if colorlinks=false) |
citebordercolor | ={0 1 0} | color of frame around citations |
urlbordercolor | ={0 1 1} | color of frame around URL links |
Please note, that explicit RGB specification is only allowed for the border colors (like linkbordercolor etc.), while the others may only assigned to named colors (which you can define your own, see Colors). In order to speed up your customization process, here is a list with the variables with their default value. Copy it in your document and make the changes you want. Next to the variables, there is a short explanations of their meaning:
\hypersetup{
bookmarks=true, % show bookmarks bar?
unicode=false, % non-Latin characters in Acrobat’s bookmarks
pdftoolbar=true, % show Acrobat’s toolbar?
pdfmenubar=true, % show Acrobat’s menu?
pdffitwindow=false, % window fit to page when opened
pdfstartview={FitH}, % fits the width of the page to the window
pdftitle={My title}, % title
pdfauthor={Author}, % author
pdfsubject={Subject}, % subject of the document
pdfcreator={Creator}, % creator of the document
pdfproducer={Producer}, % producer of the document
pdfkeywords={keyword1, key2, key3}, % list of keywords
pdfnewwindow=true, % links in new PDF window
colorlinks=false, % false: boxed links; true: colored links
linkcolor=red, % color of internal links (change box color with linkbordercolor)
citecolor=green, % color of links to bibliography
filecolor=cyan, % color of file links
urlcolor=magenta % color of external links
} |
If you don't need such a high customization, here are some smaller but useful examples. When creating PDFs destined for printing, colored links are not a good thing as they end up in gray in the final output, making it difficult to read. You can use color frames, which are not printed:
\usepackage{hyperref}
\hypersetup{colorlinks=false} |
or make links black:
\usepackage[hidelinks]{hyperref} |
or use \usepackage{hyperref} \hypersetup{hidelinks}
When you just want to provide information for the Document Info section of the PDF file, as well as enabling back references inside bibliography:
\usepackage[pdfauthor={Author's name},%
pdftitle={Document Title},%
pagebackref=true,%
pdftex]{hyperref} |
By default, URLs are printed using mono-spaced fonts. If you don't like it and you want them to be printed with the same style of the rest of the text, you can use this:
\urlstyle{same} |
Troubleshooting
[edit | edit source]Problems with Links and Equations 1
[edit | edit source]Messages like the following
! pdfTeX warning (ext4): destination with the same identifier (name{ equation.1.7.7.30}) has been already used, duplicate ignored
appear, when you have done something like
\begin{eqnarray}a=b\nonumber\end{eqnarray} |
The error disappears, if you use instead this form:
\begin{eqnarray*}a=b\end{eqnarray*} |
Beware that the shown line number is often completely different from the erroneous line.
Possible solution: Place the amsmath package before the hyperref package.
Problems with Links and Equations 2
[edit | edit source]Messages like the following
! Runaway argument? {\@firstoffive }\fi ), Some text from your document here (\ref {re\ETC. Latex Error: Paragraph ended before \Hy@setref@link was complete.
appear when you use \label
inside an align
environment.
Possible solution: Add the following to your preamble:
\AtBeginDocument{\let\textlabel\label} |
Note: The same error appears if you use a colon ":
" as part of a label, i.e. \label{lst:program01}
. Replacing that will help.
Problems with Links and Pages
[edit | edit source]Messages like the following:
! pdfTeX warning (ext4): destination with the same identifier (name{page.1}) has been already used, duplicate ignored
appear when a counter gets reinitialized, for example by using the command \mainmatter
provided by the book document class. It resets the page number counter to 1 prior to the first chapter of the book. But as the preface of the book also has a page number 1 all links to "page 1" would not be unique anymore, hence the notice that "duplicate has been ignored." The counter measure consists of putting plainpages=false
into the hyperref options. This unfortunately only helps with the page counter. An even more radical solution is to use the option hypertexnames=false
, but this will cause the page links in the index to stop working.
The best solution is to give each page a unique name by using the \pagenumbering
command:
\pagenumbering{alph} % a, b, c, ...
... titlepage, other front matter ...
\pagenumbering{roman} % i, ii, iii, iv, ...
... table of contents, table of figures, ...
\pagenumbering{arabic} % 1, 2, 3, 4, ...
... beginning of the main matter (chapter 1) ... |
Another solution is to use \pagenumbering{alph}
before the command \maketitle
, which will give the title page the label page.a. Since the page number is suppressed, it won't make a difference to the output.
By changing the page numbering every time before the counter is reset, each page gets a unique name. In this case, the pages would be numbered a, b, c, i, ii, iii, iv, v, 1, 2, 3, 4, 5, ...
If you don't want the page numbers to be visible (for example, during the front matter part), use \pagestyle{empty} ... \pagestyle{plain}
. The important point is that although the numbers are not visible, each page will have a unique name.
Another more flexible approach is to set the counter to something negative:
\setcounter{page}{-100}
... titlepage, other front matter ...
\pagenumbering{roman} % i, ii, iii, iv, ...
... table of contents, table of figures, ...
\pagenumbering{arabic} % 1, 2, 3, 4, ...
... beginning of the main matter (chapter 1) ... |
which will give the first pages a unique negative number.
The problem can also occur with the algorithms package: because each algorithm uses the same line-numbering scheme, the line identifiers for the second and follow-on algorithms will be duplicates of the first.
The problem occurs with equation identifiers if you use \nonumber
on every line of an eqnarray environment. In this case, use the *'ed form instead, e.g. \begin{eqnarray*} ... \end{eqnarray*}
(which is an unnumbered equation array), and remove the now unnecessary \nonumber
commands.
If your url's are too long and running off of the page, try using the breakurl package to split the url over multiple lines. This is especially important in a multicolumn environment where the line width is greatly shortened.
Problems with bookmarks
[edit | edit source]The text displayed by bookmarks does not always look like you expect it to look. Because bookmarks are "just text", much fewer characters are available for bookmarks than for normal LaTeX text. Hyperref will normally notice such problems and put up a warning:
Package hyperref Warning: Token not allowed in a PDFDocEncoded string:
You can now work around this problem by providing a text string for the bookmarks, which replaces the offending text:
\texorpdfstring{''TEX text''}{''Bookmark Text''} |
Math expressions are a prime candidate for this kind of problem:
\section{ \texorpdfstring{$E=mc^2$}{E=mc2} } |
which turns \section{$E=mc^2$}
to E=mc2 in the bookmark area. Color changes also do not travel well into bookmarks:
\section{ \textcolor{red}{Red !} } |
produces the string "redRed!". The command \textcolor
gets ignored but its argument (red) gets printed.
If you use:
\section{ \texorpdfstring{\textcolor{red}{Red !}}{Red\ !} } |
the result will be much more legible.
If you write your document in unicode and use the unicode option for the hyperref package you can use unicode characters in bookmarks. This will give you a much larger selection of characters to pick from when using \texorpdfstring
.
Problems with tables and figures
[edit | edit source]The links created by hyperref point to the label created within the float environment, which, as previously described, must always be set after the caption. Since the caption is usually below a figure or table, the figure or table itself will not be visible upon clicking the link[4]. A workaround exists by using the package hypcap [25] with:
\usepackage[all]{hypcap} |
Be sure to call this package after loading hyperref.
If you use the wrapfig package[5] mentioned in the "Wrapping text around figures" section of the "Floats, Figures and Captions" chapter, or other similar packages that define their own environments, you will need to manually include \capstart
in those environments, e.g.:
\begin{wrapfigure}{R}{0.5\textwidth}
\capstart
\begin{center}
\includegraphics[width=0.48\textwidth]{filename}
\end{center}
\caption{\label{labelname}a figure}
\end{wrapfigure} |
Problems with long caption and \listoffigures or long title
[edit | edit source]There is an issue when using \listoffigures
with hyperref for long captions or long titles. This happens when the captions (or the titles) are longer than the page width (about 7-9 words depending on your settings). To fix this, you need to use the option breaklinks when first declaring:
\usepackage[breaklinks]{hyperref} |
This will then cause the links in the \listoffigures
to word wrap properly.
Problems with already existing .toc, .lof and similar files
[edit | edit source]The format of some of the auxiliary files generated by latex changes when you include the hyperref package. One can therefore encounter errors like
! Argument of \Hy@setref@link has an extra }.
when the document is typeset with hyperref for the first time and these files already exist. The solution to the problem is to delete all the files that latex uses to get references right and typeset again.
Problems with footnotes and special characters
[edit | edit source]See the relevant section.
Problems with Beamer
[edit | edit source]Using the command
\hyperref[some_label]{some text} |
is broken when pointed at a label. Instead of sending the user to the desired label, upon clicking the user will be sent to the first frame. A simple work around exists; instead of using
\phantomsection\label{some_label} |
to label your frames, use
\hypertarget{some_label}{} |
and reference it with
\hyperlink{some_label}{some text} |
Problems with draft mode
[edit | edit source]WARNING! Please note that if you have activated the "draft"-option in your \documentclass declaration the hyperlinks will not show up in the table of contents, or anywhere else for that matter!!!
The hyperlinks can be re-enabled by using the "final=true" option in the following initialization of the hyperref package, just after the package was included:
\usepackage{hyperref}
\hypersetup{final=true} |
A good source of further options for the hyperref package can be found here [6].
Notes and References
[edit | edit source]- ↑ Hyperref package webpage in CTAN
- ↑ "Email link with hyperref, url packages". comp.text.tex User Group.
{{cite web}}
: Unknown parameter|accessmonthday=
ignored (help); Unknown parameter|accessyear=
ignored (|access-date=
suggested) (help) - ↑ Other possible values are defined in the hyperref manual
- ↑ http://www.ctan.org/tex-archive/macros/latex/contrib/hyperref/README
- ↑ Wrapfig package webpage in CTAN
- ↑ [1]Hyperref - Hyperlinks With LaTeX Page
Labels and Cross-referencing
[edit | edit source]Introduction
[edit | edit source]In LaTeX, you can easily reference almost anything that can be numbered, and have LaTeX automatically updating the numbering for you whenever necessary. The objects which can be referenced include chapters, sections, subsections, footnotes, theorems, equations, figures and tables[1]. The commands to be used do not depend on what you are referencing, and they are:
\label{marker}
- Used to give the object you want to reference a marker — a name which can be used to refer to that object later.
\ref{marker}
- Used to reference an object with the specified marker. This will print the number that was assigned to the object.
\pageref{marker}
- Used to print the page number where the object with the specified marker is found.
LaTeX will calculate the right numbering for the objects in the document; the marker you have used to label the object will not be shown anywhere in the document. Instead, LaTeX will replace the string "\ref{marker}
" with the right number that was assigned to the object. If you reference a marker that does not exist, the compilation of the document will be successful but LaTeX will return a warning:
LaTeX Warning: There were undefined references.
and it will replace "\ref{unknown-marker}
" with "??" — so that it will be easier to find in the document.
As you may have noticed, this way of cross-referencing is a two-step process: first the compiler has to store the labels with the right number to be used for referencing, then it has to replace the \ref
with the right number.
Because of that, you would have to compile your document twice to see the output with the proper numbering. If you only compile it once, then LaTeX will use the older information collected in previous compilations (which might be outdated), and the compiler will inform you by printing the following message at the end of the compilation:
- LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.
Using the command \pageref{}
you can help the reader to find the referenced object by providing also the page number where it can be found. You could write something like:
See figure~\ref{fig:test} on page~\pageref{fig:test}.
Since you can use exactly the same commands to reference almost anything, you might get a bit confused after you have introduced a lot of references. It is common practice among LaTeX users to add a few letters to the label to describe what you are referencing. Some packages, such as fancyref
, rely on this meta information. Here is an example:
ch: | chapter |
sec: | section |
subsec: | subsection |
fig: | figure |
tab: | table |
eq: | equation |
lst: | code listing |
itm: | enumerated list item |
alg: | algorithm |
app: | appendix subsection |
Following this convention, the label of a figure will look like \label{fig:my_figure}
, etc. You are not obligated to use these prefixes, and can in fact use any string as an argument of \label{...}
, but these prefixes can become increasingly useful as your document grows in size.
Another suggestion: try to avoid using numbers within labels. You are better off describing what the object is about. This way, if you change the order of the objects, you will not have to rename all your labels and their references.
If you want to be able to see the markers you are using in the output document as well, you can use the showkeys
package; this can become very useful as you develop your document. For more information see the Packages section.
Examples
[edit | edit source]Here are some practical examples, but you will notice that they are all the same because they all use the same commands.
Sections
[edit | edit source]\section{Greetings}
\label{sec:greetings}
Hello!
\section{Referencing}
I greeted in section~\ref{sec:greetings}.
You could place the label anywhere in the section; however, in order to avoid confusion, it is better to place it immediately after the beginning of the section. Note how the marker starts with sec:, as suggested before. The label is then referenced in a different section, where the tilde (~) indicates a non-breaking space.
Pictures
[edit | edit source]You can reference a picture by inserting it in the figure floating environment.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{gull}
\caption{Close-up of a gull}
\label{fig:gull}
\end{figure}
Figure~\ref{fig:gull} shows a photograph of a gull. |
When a label is declared within a float environment, the \ref{...}
will return the respective figure/table number, but it must occur after the caption. When declared outside, it will give the section number. To be completely safe, the label for any picture or table can go within the \caption{}
command, as follows:
\caption{Close-up of a gull\label{fig:gull}}
For more, see the Floats, Figures and Captions section about the figure
and related environments.
Fixing wrong labels
[edit | edit source]The command \label
must appear after (or inside) \caption
. Otherwise, it will pick up the current section or the list number instead of what is intended.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{gull}
\caption{Close-up of a gull} \label{fig:gull}
\end{figure}
Issues with links to tables and figures handled by hyperref
[edit | edit source]In case you use the package hyperref
to create a PDF, the link to a table or a figure will point to its caption instead, which is always below the table or the figure itself[2]. As a result, the table or the figure will not be visible if it is above the pointer, which means that some scrolling-up would be required. If you want the link to point to the top of the image, you can give the option hypcap
to the caption
package[3]:
\usepackage{caption} % hypcap is true by default so [hypcap=true] is optional in \usepackage[hypcap=true]{caption}
Formulae
[edit | edit source]Here is an example showing how to reference formulae:
\begin{equation} \label{eq:solve}
x^2 - 5 x + 6 = 0
\end{equation}
\begin{equation}
x_1 = \frac{5 + \sqrt{25 - 4 \times 6}}{2} = 3
\end{equation}
\begin{equation}
x_2 = \frac{5 - \sqrt{25 - 4 \times 6}}{2} = 2
\end{equation}
and so we have solved equation~\eqref{eq:solve} |
Here, notice the eq: prefix in the label — and that the label is placed soon after the beginning of the math mode. To reference a formula, an environment with counter would have to be used. Most of the times, you will be using the equation
environment, as that's usually the best choice for one-line formulae whether you are using amsmath
or not.
eqref
[edit | edit source]The amsmath
package adds a new command for referencing formulae; it is \eqref{}
. It works exactly like \ref{}
, but adds parentheses so that instead of printing a plain number as 5, it will print (5). This can be useful to help the reader distinguish between formulae and other things, without the need to repeat the word "formula" before any reference.[4] Its output can be changed as desired; for more information see the amsmath
documentation.
tag
[edit | edit source]The \tag{eqnno}
command is used to manually set equation numbers, where eqnno is the text string you want to display instead of the usual equation number. It is normally better to use labels, but sometimes hard-coded equation numbers might offer a useful work-around — such as the case where you want to repeat an equation that has already been used before (e.g. \tag{\ref{eqn:before}}
).
numberwithin
[edit | edit source]The amsmath
package adds the \numberwithin{countera}{counterb}
command, which replaces the simple countera
with a more sophisticated
counterb.countera
. For example, \numberwithin{equation}{section}
in the preamble will prepend the section number to all equation numbers.
cases
[edit | edit source]The cases
package adds the \numcases
and the \subnumcases
commands, which produce multi-case equations with a separate equation number and a separate equation number plus a letter, respectively, for each case.
The varioref package
[edit | edit source]The varioref
package introduces a new command called \vref{}
. This command is used exactly like the basic \ref
, but it has a different output according to the context. If the object to be referenced is in the same page, it works just like \ref
; if the object is far away, it will print something like "5 on page 25", i.e. it adds the page number automatically. If the object is close, it can use more refined sentences such as "on the next page" or "on the facing page" automatically — according to the context and the document class.
This command has to be used very carefully. It outputs more than one word, so it may happen that its output falls on two different pages. In this case, the algorithm can get confused and cause a loop.
For example, you could label an object on page 23 and the \vref
output could happen to stay between page 23 and 24. If it were on page 23, it would print like the basic ref
, if it were on page 24, it would print "on the previous page", but it is on both, and this may cause some strange errors at compiling time that could be very difficult to fix.
And while for small documents, these situations might happen very rarely, for long documents spanning hundreds of references, these situations are more likely to happen. One way to avoid these problems during document preparation is to use the standard ref
all the way through at first, convert all to vref
when the document is close to its final version — before making the adjustment to fix any possible problem.
The hyperref package
[edit | edit source]autoref
[edit | edit source]The hyperref
package introduces another useful command; \autoref{}
. This command creates a reference with additional text corresponding to the target's type, all of which will be a hyperlink. For example, the command \autoref{sec:intro}
would create a hyperlink to the \label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (the full list of default names can be found here). Note that, while there's an \autoref*
command that produces an unlinked prefix (useful if the label is on the same page as the reference), no alternative \Autoref
command is defined to produce capitalized versions (useful, for instance, when starting sentences); but since the capitalization of autoref names was chosen by the package author, you can customize the prefixed text by redefining \typeautorefname
to the prefix you want, as in:
\def\sectionautorefname{Section}
This renaming trick can, of course, be used for other purposes as well.
- If you would like to have a hyperlink reference without the predefined text
\autoref{}
provides, then you change this with a command such as\hyperref[sec:intro]{Appendix~\ref*{sec:intro}}
. Note that you can disable the creation of hyperlinks inhyperref
, and just use these commands for automatic text.
- Keep in mind that the \label must be placed inside an environment with a counter, such as a table or a figure. Otherwise, not only will the number refer to the current section (as mentioned above), but the name might refer to the previous environment with a counter as well. For example, if you put a label after closing a figure, the label will still say "figure n", on which n is the current section number.
nameref
[edit | edit source]The hyperref
package also automatically includes the nameref
package, and a similarly named command. It is similar to \autoref{}
, but inserts text corresponding to the section name, for example.
Input:
\section{MyFirstSection} \label{sec:marker}
\section{MySecondSection}
In section~\nameref{sec:marker} we defined...
Output:
In section MyFirstSection we defined...
Anchor manual positioning
[edit | edit source]When you define a \label
outside a figure, a table, or other floating objects, the label points to the current section. In some cases, this behavior is not what you'd like and you'd prefer the generated link to point to the line where the \label
is defined. This can be achieved with the command
\phantomsection
as in this example:
%The link location will be placed on the line below.
\phantomsection
\label{the_label}
The cleveref package
[edit | edit source]The cleveref
package introduces the new command \cref{}
which includes the type of referenced object like \autoref{}
does. The alternate \labelcref{}
command works more like standard \ref{}
. References to pages are handled by the \cpageref{}
command.
- Use
\crefrange{}{}
and\cpagerefrange{}
commands for start and end label in either order and to provide a natural language (babel
enabled) range. - Use
\cref{}
command for multiple or single references (on single line), it will sort them and group into ranges automatically in very convenient format like ` item 2 to 4 and 6 to 19.`.[5] - Use
\labelcref{}
where the numbers would be a references to the labels and [sorted] output as in previous paragraph
The format can be specified in the preamble.
Interpackage interactions for varioref , hyperref , and cleveref
[edit | edit source]Because varioref
,hyperref
, and cleveref
redefine the same commands, they can produce unexpected results when their \usepackage
commands appear in the preamble in the wrong order. For example, using hyperref
,varioref
, then cleveref
can cause \vref{}
to fail as though the marker were undefined.[6] The following order generally seems to work:
varioref
hyperref
cleveref
[6]
See also
[edit | edit source]Notes and References
[edit | edit source]- ↑ Advantages of LaTeX — Automatic Numbering and Robust Citation System
- ↑ http://www.ctan.org/tex-archive/macros/latex/contrib/hyperref/README
- ↑ Documentation of the
caption
package — 6.5hyperref
- ↑ TeX StackExchange — What is the difference between \eqref and \ref?
- ↑ TeX Blog — Cleveref, a clever way to reference in LaTeX
- ↑ a b Tests done under report class http://tex.stackexchange.com/questions/139459/vref-and-input-command
Errors and Warnings
[edit | edit source]LaTeX describes what it is typesetting while it does it. If it encounters something it doesn't understand or can't do, it will display a message saying what is wrong. It may also display warnings for less serious conditions.
Don't panic if you see error messages: it is very common to mistype or misspell commands, forget curly braces, type a forward slash instead of a backslash, or use a special character by mistake. Errors are easily spotted and easily corrected in your editor, and you can then run LaTeX again to check you have fixed everything. Some of the most common errors are described in the next sections.
Error messages
[edit | edit source]The format of an error message is always the same. Error messages begin with an exclamation mark at the start of the line, and give a description of the error, followed by another line starting with the number, which refers to the line-number in your document file which LaTeX was processing when the error was spotted. Here's an example, showing that the user mistyped the \tableofcontents command:
! Undefined control sequence. l.6 \tableofcotnetns
When LaTeX finds an error like this, it displays the error message and pauses. You must type one of the following letters to continue:
Key | Meaning |
---|---|
x | Stop immediately and exit the program. |
q | Carry on quietly as best you can and don't bother me with any more error messages. |
e | Stop the program but re-position the text in my editor at the point where you found the error (This only works if you're using an editor which LaTeX can communicate with). |
h | Try to give me more help. |
i | (followed by a correction) means input the correction in place of the error and carry on (This is only a temporary fix to get the file processed. You still have to make that correction in the editor). |
r | run in non-stop mode. Plow through any errors, unless too many pile up and it fails (100 errors). |
Some systems (Emacs is one example) run LaTeX with a "nonstop" switch turned on, so it will always process through to the end of the file, regardless of errors, or until a limit is reached.
Warnings
[edit | edit source]Warnings don't begin with an exclamation mark: they are just comments by LaTeX about things you might want to look into, such as overlong or underrun lines (often caused by unusual hyphenations, for example), pages running short or long, and other typographical niceties (most of which you can ignore until later). Unlike other systems, which try to hide unevennesses in the text (usually unsuccessfully) by interfering with the letter spacing, LaTeX takes the view that the author or editor should be able to contribute. While it is certainly possible to set LaTeX's parameters so that the spacing is sufficiently sloppy that you will almost never get a warning about badly-fitting lines or pages, you will almost certainly just be delaying matters until you start to get complaints from your readers or publishers.
Examples
[edit | edit source]Only a few common error messages are given here: those most likely to be encountered by beginners. If you find another error message not shown here, and it's not clear what you should do, ask for help.
Most error messages are self-explanatory, but be aware that the place where LaTeX spots and reports an error may be later in the file than the place where it actually occurred. For example if you forget to close a curly brace which encloses, say, italics, LaTeX won't report this until something else occurs which can't happen until the curly brace is encountered (e.g. the end of the document!) Some errors can only be righted by humans who can read and understand what the document is supposed to mean or look like.
Newcomers should remember to check the list of special characters: a very large number of errors when you are learning LaTeX are due to accidentally typing a special character when you didn't mean to. This disappears after a few days as you get used to them.
Too many }'s
[edit | edit source]! Too many }'s. l.6 \date December 2004}
The reason LaTeX thinks there are too many }'s here is that the opening curly brace is missing after the \date control sequence and before the word December, so the closing curly brace is seen as one too many (which it is!). In fact, there are other things which can follow the \date command apart from a date in curly braces, so LaTeX cannot possibly guess that you've missed out the opening curly brace until it finds a closing one!
Undefined control sequence
[edit | edit source]! Undefined control sequence. l.6 \dtae {December 2004}
In this example, LaTeX is complaining that it has no such command ("control sequence") as \dtae. Obviously it's been mistyped, but only a human can detect that fact: all LaTeX knows is that \dtae is not a command it knows about: it's undefined. Mistypings are the most common source of errors. Some editors allow common commands and environments to be inserted using drop-down menus or icons, which may be used to avoid these errors.
Not in Mathematics Mode
[edit | edit source]! Missing $ inserted
A character that can only be used in the mathematics mode was inserted in normal text. If you intended to use mathematics mode, then use $...$ or \begin{math}...\end{math} or use the 'quick math mode': \ensuremath{...}. If you did not intend to use mathematics mode, then perhaps you are trying to use a special character that needs to be entered in a different way; for example _ will be interpreted as a subscript operator in mathematics mode, and you need \_ to get an underscore character.
Since 2018[1], all TeX engines support UTF-8 encoding. In older versions, this can also happen if you use the wrong character encoding, for example using UTF-8 without "\usepackage[utf8]{inputenc}" or using iso8859-1 without "\usepackage[latin1]{inputenc}".
Runaway argument
[edit | edit source]Runaway argument? {December 2004 \maketitle ! Paragraph ended before \date was complete. <to be read again> \par l.8
In this error, the closing curly brace has been omitted from the date. It's the opposite of the error of too many }'s, and it results in \maketitle trying to format the title page while LaTeX is still expecting more text for the date! As \maketitle creates new paragraphs on the title page, this is detected and LaTeX complains that the previous paragraph has ended but \date is not yet finished.
Underfull hbox
[edit | edit source]Underfull \hbox (badness 1394) in paragraph at lines 28--30 [][]\LY1/brm/b/n/10 Bull, RJ: \LY1/brm/m/n/10 Ac-count-ing in Busi- [94]
This is a warning that LaTeX cannot stretch the line wide enough to fit, without making the spacing bigger than its currently permitted maximum. The badness (0-10,000) indicates how severe this is (here you can probably ignore a badness of 1394). It says what lines of your file it was typesetting when it found this, and the number in square brackets is the number of the page onto which the offending line was printed. The codes separated by slashes are the typeface and font style and size used in the line. Ignore them for the moment.
This comes up if you force a linebreak, e.g., \\, and have a return before it. Normally TeX ignores linebreaks, providing full paragraphs to ragged text. In this case it is necessary to pull the linebreak up one line to the end of the previous sentence.
This warning may also appear when inserting images. It can be avoided by using the \textwidth or possibly \linewidth options, e.g. \includegraphics[width=\textwidth]{image_name}
Overfull hbox
[edit | edit source][101] Overfull \hbox (9.11617pt too wide) in paragraph at lines 860--861 []\LY1/brm/m/n/10 Windows, \LY1/brm/m/it/10 see \LY1/brm/m/n/10 X Win-
An overfull \hbox means that there is a hyphenation or justification problem: moving the last word on the line to the next line would make the spaces in the line wider than the current limit; keeping the word on the line would make the spaces smaller than the current limit, so the word is left on the line, but with the minimum allowed space between words, and which makes the line go over the edge.
The warning is given so that you can find the line in the code that originates the problem (in this case: 860-861) and fix it. The line on this example is too long by a shade over 9pt. The chosen hyphenation point which minimizes the error is shown at the end of the line (Win-). Line numbers and page numbers are given as before. In this case, 9pt is too much to ignore (over 3mm), and a manual correction needs making (such as a change to the hyphenation), or the flexibility settings need changing.
If the "overfull" word includes a forward slash, such as "input/output
", this should be properly typeset as "input\slash output
". The use of \slash
has the same effect as using the "/
" character, except that it can form the end of a line (with the following words appearing at the start of the next line). The "/
" character is typically used in units, such as "mm/year
" character, which should not be broken over multiple lines.
The warning can also be issued when the \end{document} tag was not included or was deleted.
Easily spotting overfull hboxes in the document
[edit | edit source]To easily find the location of overfull hbox in your document, you can make latex add a black bar where a line is too wide:
\overfullrule=2cm |
Missing package
[edit | edit source]! LaTeX Error: File `paralisy.sty' not found. Type X to quit or <RETURN> to proceed, or enter new name. (Default extension: sty) Enter file name:
When you use the \usepackage command to request LaTeX to use a certain package, it will look for a file with the specified name and the filetype .sty. In this case the user has mistyped the name of the paralist package, so it's easy to fix. However, if you get the name right, but the package is not installed on your machine, you will need to download and install it before continuing. If you don't want to affect the global installation of the machine, you can simply download from Internet the necessary .sty file and put it in the same folder of the document you are compiling.
Package babel Warning: No hyphenation patterns were loaded for the language X
[edit | edit source]Although this is a warning from the Babel package and not from LaTeX, this error is very common and (can) give some strange hyphenation (word breaking) problems in your document. Wrong hyphenation rules can decrease the neatness of your document.
Package babel Warning: No hyphenation patterns were loaded for (babel) the language `Latin' (babel) I will use the patterns loaded for \language=0 instead.
This can happen after the usage of: (see LaTeX/Internationalization)
\usepackage[latin]{babel}
The solution is not difficult, just install the used language in your LaTeX distribution.
Package babel Error: You haven't loaded the option X yet.
[edit | edit source]If you previously set the X language, and then decided to switch to Y, you will get this error. This may seem awkward, as there is obviously no error in your code if you did not change anything. The answer lies in the .aux file, where babel defined your language. If you try the compilation a second time, it should work. If not, delete the .aux file, then everything will work as usual.
No error message, but won't compile
[edit | edit source] A reader requests expansion of this section to include more material. You can help by adding new material (learn how) or ask for assistance in the reading room. |
One common cause of (pdf)LaTeX getting stuck is forgetting to include \end{document}
Software that can check your .tex Code
[edit | edit source]There are several programs capable of checking LaTeX source, with the aim of finding errors or highlighting bad practice, and providing more help to (particularly novice) users than the built-in error messages.
- nag (www.ctan.org/tex-archive/macros/latex/contrib/nag) is a LaTeX package designed to indicate the use of obsolete commands.
- lacheck (www.ctan.org/tex-archive/support/lacheck) is a consistency checker intended to spot mistakes in code. It is available as source code or compiled for Windows and OS/2
- chktex (baruch.ev-en.org/proj/chktex/) is a LaTeX semantic checker available as source code for Unix-like systems.
Lengths
[edit | edit source]In TeX, a length is
- a floating point number followed by a unit, optionally followed by a stretching value;
3.5pt plus 1pt minus 2pt |
- a floating point factor followed by a macro that expands to a length.
1.7\textwidth |
Units
[edit | edit source]First, we introduce the LaTeX measurement units. All LaTeX units are two-letter abbreviations. You can choose from a variety of units. Here are the most common ones.[2]
Abbreviation | Definition | Value in points (pt) | Value in micrometers (µm) |
---|---|---|---|
pt | a point is 1/72.27 inch, that means about 0.0138 inch. | 1 | 351.46 |
mm | a millimeter | 2.84 = 7227/2540 | 1000 |
cm | a centimeter | 28.4 = 7227/254 | 10000 |
in | inch | 72.27 | 25400 |
ex | roughly the height of an 'x' in the current font | undefined, depends on the font used | |
em | roughly the width of an 'M' (uppercase) in the current font | undefined, depends on the font used |
The point is the default unit and 1pt is the default length. All other units are converted to the point by a fixed ratio.
Here are some less common units.[3]
Abbreviation | Definition | Value in points (pt) | Value in micrometers (µm) |
---|---|---|---|
bp | a big point is 1/72 inch, that means about 0.0139 inch. | 1.00375 = 803/800 | 352 7/9 |
pc | pica | 12 | 4218 |
dd | didot | 1.070 = 1238/1157 | 376 |
cc | cicero (12 didot) | 12.84 = 14856/1157 | 4512 |
nd | new didot | 1.067 = 685/642 | 375 |
nc | new cicero (12 new didot) | 12.80 = 1370/107 | 4500 |
sp | scaled point | 0.000015 = 1/65536 | 0.00536 |
Box lengths
[edit | edit source]A box in TeX is characterized by three lengths:
- depth
- height
- width
See Boxes.
Length manipulation
[edit | edit source]You can change the values of the variables defining the page layout with two commands. With this one you can set a new value for an existing length variable:
\setlength{\mylength}{length} |
with this other one, you can add a value to the existing one:
\addtolength{\mylength}{length} |
You can create your own length with the command, and you must create a new length before you attempt to set it:
\newlength{\mylength} |
You may also set a length from the size of a text with one of these commands:
\settowidth{\mylength}{some text}
\settoheight{\mylength}{some text}
\settodepth{\mylength}{some text} |
The calc package provides also the function \settototalheight{\mylength}{some text}
When using these commands, you may duplicate the text that you want to use as reference if you plan to also display it. But LaTeX also provides \savebox
to avoid this duplication.
You may wish to look at the example below to see how you can use these. See Boxes for more details.
You can also define stretched values. A stretching value is a length preceded by plus
or minus
to specify to what extent tex is authorized to change the length. Example:
\setlength{\parskip}{10pt plus 5pt minus 3pt} |
It means that tex will try to use a length of 10pt; if it is underfull, it will raise the length up to a maximum of 15pt; if it is overfull, it will lower the length up to a minimum of 7pt.
Note that it is not mandatory to specify both the plus and the minus values, but if you do, plus must be placed before minus.
To print a length, you can use the \the
command:
\the\textwidth |
Plain TeX
[edit | edit source]To create a new length:
\newdimen\mylength |
To set a length:
\mylength=1.5in |
To view, it is the same as with LaTeX, using the command \the
.
LaTeX default lengths
[edit | edit source]Common length macros are:
- \baselineskip
- The normal vertical distance between lines in a paragraph.
- \baselinestretch
- A factor multiplying \baselineskip. Has to be set with
\renewcommand{\baselinestretch}{factor}
- \columnsep
- The distance between columns.
- \columnwidth
- The width of the column.
- \evensidemargin
- The margin for 'even' pages (think of a printed booklet).
- \linewidth
- The width of a line in the local environment.
- \oddsidemargin
- The margin for 'odd' pages (think of a printed booklet).
- \paperwidth
- The width of the page.
- \paperheight
- The height of the page.
- \parindent
- The normal paragraph indentation.
- \parskip
- The extra vertical space between paragraphs.
- \tabcolsep
- The default separation between columns in a tabular environment.
- \textheight
- The height of text on the page.
- \textwidth
- The width of the text on the page.
- \topmargin
- The size of the top margin.
- \unitlength
- Units of length in picture environment.
Fixed-length spaces
[edit | edit source]To insert a fixed-length space, use:
\hspace{length}
\vspace{length} |
\hspace
stands for horizontal space, \vspace
for vertical space.
If such a space should be kept even if it falls at the end or the start of a line, use \hspace*
instead.
If the space should be preserved at the top or at the bottom of a page, use the starred version of the command, \vspace*
, instead of \vspace
.
If you want to add space at the beginning of the document, without anything else written before, then you may use
{ \vspace*{length} } |
It's important you use the \vspace*
command instead of \vspace
, otherwise LaTeX can silently ignore the extra space.
TeX features some macros for fixed-length spacing.
\smallskip
- Inserts a small space in vertical mode (between two paragraphs).
\medskip
- Inserts a medium space in vertical mode (between two paragraphs).
\bigskip
- Inserts a big space in vertical mode (between two paragraphs).
The vertical mode is during the process of assembling boxes "vertically", like paragraphs to build a page. The horizontal mode is during the process of assembling boxes "horizontally", like letters to build a word or words to build a paragraph.
The fact they are vertical mode commands mean they will be ignored (or fail) in horizontal mode such as in the middle of a paragraph. The first token next to a double linebreak is still in vertical mode if it does not expand to characters.
% WRONG!
Some words.
\bigskip
Let's continue.
%% CORRECT!
Some words.
\bigskip
Let's continue. |
Rubber/Stretching lengths
[edit | edit source]The command:
\stretch{factor} |
generates a special rubber space where factor is a number, possibly a float. It stretches until all the remaining space on a line is filled up. If two \hspace{\stretch{factor
}} commands are issued on the same line, they grow according to the stretch factor.
x \hspace{ \stretch{1} } x \hspace{ \stretch{3} } x |
x x x |
The same way, you can stretch vertically:
\maketitle
\vspace{ \stretch{1} }
Some comments.
\vspace{ \stretch{1} }
\tableofcontents |
You can also use \fill
instead of \stretch{1}
.
The \stretch
command, in connection with \pagebreak
, can be used to typeset text on the last line of a page, or to center text vertically on a page.
There are 'shortcut commands' for stretching with factor 1 (i.e. with \stretch{1}
or \fill
): \hfill
and \vfill
.
Example:
\maketitle
\vfill
Some comments.
\vfill
\tableofcontents |
Fill the rest of the line
[edit | edit source]Several macros allow filling the rest of the line -- or stretching parts of the line -- in different manners.
\hfill
will produce empty space.\dotfill
will produce dots.\hrulefill
will produce a rule.
Examples
[edit | edit source]Resize an image to take exactly half the text width :
\includegraphics[width=0.5\textwidth]{mygraphic} |
Make distance between items larger (inside an itemize environment) :
\addtolength{\itemsep}{0.5\baselineskip} |
Use of \savebox
to resize an image to the height of the text:
% Create the holders we will need for our work
\newlength{\mytitleheight}
\newsavebox{\mytitletext}
% Create the reference text for measures
\savebox{\mytitletext}{%
\Large\bfseries This is our title%
}
\settoheight{\mytitleheight}{ \usebox{\mytitletext} }
% Now creates the actual object in our document
\framebox[\textwidth][l]{%
\includegraphics[height=\mytitleheight]{my_image}%
\hspace{2mm}%
\usebox{\mytitletext}%
} |
References
[edit | edit source]- ↑ LaTeX news 2018 (Retrieved March 23, 2024)
- ↑ http://www.giss.nasa.gov/tools/latex/ltx-86.html
- ↑ http://anonscm.debian.org/cgit/debian-tex/texlive-bin.git/tree/texk/web2c/pdftexdir/pdftex.web?h=debian/2015.20150524.37493-5#n10460
See also
[edit | edit source]- University of Cambridge > Engineering Department > computing help > LaTeX > Squeezing Space in LaTeX
Counters
[edit | edit source]Counters are an essential part of LaTeX: they allow you to control the numbering mechanism of everything (sections, lists, captions, etc.). To that end each counter stores an integer value in the range of long integer, i.e., from to . [26]
Counter manipulation
[edit | edit source]In LaTeX it is fairly easy to create new counters and even counters that reset automatically when another counter is increased (think subsection in a section for example). With the command
\newcounter{NameOfTheNewCounter} |
you create a new counter that is automatically set to zero. If you want the counter to be reset to zero every time another counter is increased, use:
\newcounter{NameOfTheNewCounter}[NameOfTheOtherCounter] |
For example, if you want to enumerate the equations in each chapter independently, you can create something like an "equationschapter" counter that will be automatically reset at the begin of each section.
\newcounter{equationschapter}[section]
\section{First Section}
I present one equation:
\stepcounter{equationschapter} $a=b+c$ (Eq. \arabic{section}.\arabic{equationschapter})
\section{Second Section}
I present more equations:
\stepcounter{equationschapter} $a=c+d$ (Eq. \arabic{section}.\arabic{equationschapter})
\stepcounter{equationschapter} $d=e$ (Eq. \arabic{section}.\arabic{equationschapter}) |
To add to an existing counter another counter causing a reset when increased, use:
\counterwithin*{NameOfTheCounter}{NameOfTheOtherCounter} |
If this doesn't work it might be because of an old LaTeX version, the following should work in that case:
\makeatletter
\@addtoreset{NameOfTheCounter}{NameOfTheOtherCounter}
\makeatother |
To undo this effect one can use:
\counterwithout*{NameOfTheCounter}{NameOfTheOtherCounter} |
or:
\makeatletter
\@removefromreset{NameOfTheCounter}{NameOfTheOtherCounter}
\makeatother |
To increase the counter, either use
\stepcounter{NameOfTheNewCounter} |
or
\refstepcounter{NameOfTheNewCounter} % used for labels and cross referencing |
or
\addtocounter{NameOfTheNewCounter}{number} |
here the number can also be negative. For automatic resetting you need to use \stepcounter
.
To set the counter value explicitly, use
\setcounter{NameOfTheNewCounter}{number} |
Counter access
[edit | edit source]There are several ways to get access to a counter.
\theNameOfTheNewCounter
will print the formatted string related to the counter (note the "the" before the actual name of the counter).\value{NameOfTheNewCounter}
will return the counter value which can be used by other counters or for calculations. It is not a formatted string, so it cannot be used in text.\arabic{NameOfTheNewCounter}
will print the formatted counter using arabic numbers.
Note that \arabic{NameOfTheNewCounter}
may be used as a value too, but not the others.
Strangely enough, LaTeX counters are not introduced by a backslash in any case, even with the \the
command. plainTeX equivalents \count
and \newcount\mycounter
do abide by the backslash rule.
Counter style
[edit | edit source]The following internal LaTeX commands will convert numeric value of specified counter into printable string and insert string into document:
\arabic
- Numbers from to inclusive converted to strings «-2147483648», «-2147483647», …, «-1», «0», «1», …, «2147483646», «2147483647».
- Example: 1, 2, 3, …
\alph
- Numbers from 1 to 26 inclusive converted to strings «a», «b», …, «z». Other numbers (negative numbers, zero, 27, 28, …, ) converted to empty string.
- Example: a, b, c, …
\Alph
- Same as
\alph
, but upper case letters used. - Example: A, B, C, …
\roman
- Numbers from 1 to 4999 inclusive converted to strings «i» (1), «ii» (2), …, «mmmmcmxcix» (4999), where «i» — 1, «v» — 5, «x» — 10, «l» — 50, «c» — 100, «d» — 500, «m» — 1000. Numbers from 5000 to inclusive converted to strings «mmmmm» (5000), «mmmmmi» (5001), …. Other numbers (negative numbers, zero) converted to empty string.
- Example: i, ii, iii, …
\Roman
- Same as
\roman
, but upper case letters used. - Example: I, II, III, …
\fnsymbol
- Aimed at footnotes; prints a sequence of symbols.
Number Symbol(s) 1 ∗ 2 † 3 ‡ 4 § 5 ¶ 6 ∥ 7 ∗∗ 8 †† 9 ‡‡ Other numbers Empty string
- Example: ∗, †, ‡, …
LaTeX default counters
[edit | edit source]- part
- chapter
- section
- subsection
- subsubsection
- paragraph
- subparagraph
- page
- figure
- table
- footnote
- mpfootnote
For the enumerate environment:
- enumi
- enumii
- enumiii
- enumiv
For the eqnarray environment:
- equation
Book with parts, sections, but no chapters
[edit | edit source]Here follows an example where we want to use parts and sections, but no chapters in the book class :
\renewcommand{\thesection}{\thepart .\arabic{section}}
\part{My Part}
\section{My Section}
\subsection{My Subsection} |
Custom enumerate
[edit | edit source]See the List Structures chapter.
Custom sectioning
[edit | edit source]Here is an example for recreating something similar to a section and subsection counter that already exist in LaTeX:
\newcounter{mysection}
\newcounter{mysubsection}[mysection]
\addtocounter{mysection}{2} % set them to some other numbers than 0
\addtocounter{mysubsection}{10} % same
%
\arabic{mysection}.\arabic{mysubsection}
Blah blah
\stepcounter{mysection}
\arabic{mysection}.\arabic{mysubsection}
Blah blah
\stepcounter{mysubsection}
\arabic{mysection}.\arabic{mysubsection}
Blah blah
\addtocounter{mysubsection}{25}
\arabic{mysection}.\arabic{mysubsection}
Blah blah and more blah blah |
Boxes
[edit | edit source] This page may need to be updated to reflect current knowledge. You can help update it, discuss progress, or request assistance. |
This module may require a complete rewrite in order to suit its intended audience. You can help rewrite it. Please see the relevant discussion. |
TeX boxes and glue overview
[edit | edit source]A box is the TeX term for an invisible container that can hold a visible element, nothing, or other boxes. Glue is the TeX term for an invisible connector that determines the relative position of joined boxes. Each separate visible element contained within a TeX document is contained within a box. A visible element can be a letter, image, geometric shape, etc. TeX builds pages by gluing boxes together according to the default TeX rules, default LaTeX rules, or document commands. In a typical document, letter boxes are glued to other letter boxes to form words, which are then elastically glued to other words to form sentences. Sentences are broken into lines and placed in paragraph boxes. Elastic glue is squeezed or stretched to fully justify lines within paragraph boxes. Paragraph boxes are glued to diagram boxes, and so on.
While it is true that boxes can hold other boxes, not all commands that can generate boxes can be used within all other commands that can generate boxes. There are often workarounds for these limitations.
The size of a box is typically related to the size and position of its contents, but it doesn't have to be. Many box commands accept custom widths and/or heights, and there are other commands that affect the shape and position of boxes. Boxes are placed relative to other boxes, while visible elements are placed relative to the boxes which contain them.
A more complete description of boxes and glue can be found in chapters 11 and 12 of Donald E. Knuth's, 'The TeXbook'. A list of basic LaTeX box and glue commands can be found at http://www.personal.ceu.hu/tex/spacebox.htm .
boxes
[edit | edit source]character boxes
[edit | edit source]TeX character boxes have three dimensional properties:
- The height is the length between the baseline and the top of the box.
- The depth is the length between the baseline and the bottom of the box.
- The width is the width of the box.
Character boxes are glued together at the baseline.
parbox, minipage, and pbox
[edit | edit source]A \parbox
is a box of specific width formatted in paragraph mode. In paragraph mode, text is broken into lines and lines are broken into pages.
\parbox[pos][height][contentpos]{width}{text}
width defines the width of the paragraph box. Text will be broken into lines so that it fits within this width. Besides fixed lengths, you can also provide user defined length macros or TeX/LaTeX defined length macros and primitives such as \width
, \height
, \depth
and \totalheight
. (See character box above for explanations of depth and height.)
height defines the height of the \parbox
.
pos selects which baseline to join. It can be top, bottom, or center. This parameter is often confusing to new users! See the special note below.
contentpos positions the contents of the box within the box. It can be one of center, top, bottom or spread. Note that contentpos has no effect if the box is not larger than the text it contains.
\pbox
is available in the pbox package. A \pbox
has the same parameters as a \parbox
, but if the user provided width parameter is larger than the actual contents of the pbox the pbox shrinks to fit the content. This is only useful if the content contains manual line breaks and you wish to fit the resulting material.
\pbox[pos][height]{width}{text}
The minipage environment takes the same parameters as a \parbox
, and behaves nearly identically to it. The difference between a minipage and a \parbox
is that a \parbox
can only contain a single paragraph and you cannot use all commands and environments inside it, while a minipage may contain multiple paragraphs and, in fact, almost anything.
\begin{minipage}[pos][height][contentpos]{width} text \end{minipage}
You can make use of minipage, \parbox
, and \pbox
to embed paragraphs in non-paragraph boxes. For instance:
\fbox{%
\parbox{\textwidth}{
Some very long text\\
that would not be allowed\\
in an fbox.
}%
} |
special notes on the pos parameter
[edit | edit source]The pos alignment parameter does not refer to the \parbox
's borders when contentpos is either missing or equal to pos and anytime pos= center! Under any of these circumstances the alignment parameter selects which line of text within the \parbox
will be used to align the paragraph box. The \parbox
is placed so the baseline of that chosen line of text is aligned to the baseline of the box that the \parbox
is glued to. Thus, if the pos is set top, the baseline of the top line of text in the \parbox
will line up with the baseline outside of the \parbox
. In the special case of a parbox that has only one line of text, that one and only line of text is the top, bottom, and center line of text simultaneously, and changing pos will appear to do nothing unless additional text is added.
If the contentpos is present and not the same as pos and pos is not center, the \parbox
will align at its borders.
makebox and mbox
[edit | edit source]Makebox creates a single-line box, optionally of fixed width, but otherwise large enough to hold its contents. Note that the width does not have to be wider than the contents: for instance, setting width to 0 typesets the content without changing the current position. (E.g., this would allow for an overstrike.) Makebox is typically used to prevent hyphenation (see Hyphenation) or simply to keep text that belongs together from being placed on separate lines. You cannot place line breaks (\\) within a Makebox. mbox is the shorthand no-option version of Makebox.
\mbox{text}
\makebox[width][pos]{text} |
The pos parameter takes a one letter value: center, flushleft, flushright, or spread the text to fill the box.
\makebox[0pt]{Some text} over this text
\makebox[15ex][s]{Censored text}\hspace{-15ex}\makebox[15ex][s]{X X X X X}
Text \makebox[2\width][r]{running away} |
framebox and fbox
[edit | edit source]The command \framebox
behaves identically to \makebox
except that it additionally draws a box around its contents.
\fbox{text}
\framebox[width][pos]{text} |
The following example shows you some things you could do with the \makebox
and \framebox
commands:
\makebox[\textwidth]{c e n t r a l} \par
\makebox[\textwidth][s]{s p r e a d} \par
\framebox[1.1\width]{Guess I'm framed now!} \par
\framebox[0.8\width][r]{Bummer, I am too wide} \par
\framebox[1cm][l]{never mind, so am I}
Can you read this? |
You can tweak the following frame lengths.
\fboxsep
: the distance between the frame and the content.\fboxrule
: the thickness of the rule.
This prints a thick and more distant frame:
\setlength{\fboxsep}{10pt}
\setlength{\fboxrule}{5pt}
\fbox{A frame.} |
This shows the box frame of a letter.
\setlength{\fboxsep}{0pt}
\fbox{A} |
The framed package is available that adds the framed environment which provides an an easy way to frame a paragraph within a document:
\usepackage{framed}
% ...
\begin{framed}
This is an easy way to box text within a document!
\end{framed} |
savebox/usebox/newsavebox
[edit | edit source]A savebox is a non-rendered box that is saved for later repeated rendering via the usebox command.
\newsavebox{\boxname}
\savebox{\boxname}{some content}
\usebox{\boxname} |
The command \newsavebox
creates a placeholder for storing content;
the command \savebox
stores the specified content in the placeholder without rendering it in the document; and \usebox
renders the content of the placeholder into the document.
colorbox and fcolorbox
[edit | edit source]See Colors.
\fcolorbox
can also be tweaked with \fboxsep
and \fboxrule
.
fancybox
[edit | edit source]The fancybox package provides additional boxes.
\doublebox
\ovalbox
\shadowbox
box modifiers
[edit | edit source]raisebox
[edit | edit source]Now that we control the horizontal, the obvious next step is to go for the vertical. No problem for LaTeX. The
\raisebox{lift}[height][depth]{text} |
command lets you define the vertical properties of a box. You can use \width
, \height
, \depth
and \totalheight
in the first three parameters, in order to act upon the size of the box inside the text argument. The two optional parameters set for the height and depth of the raisebox. For instance you can observe the difference when embedded in a framebox.
\raisebox{0pt}[0pt][0pt]{\Large%
\textbf{Aaaa\raisebox{-0.3ex}{a}%
\raisebox{-0.7ex}{aa}%
\raisebox{-1.2ex}{r}%
\raisebox{-2.2ex}{g}%
\raisebox{-4.5ex}{h}
}
}
he shouted but not even the next
one in line noticed that something
terrible had happened to him. |
rotatebox
[edit | edit source]See Rotations.
resizebox and scalebox
[edit | edit source]The graphicx package features additional boxes.
\resizebox{10ex}{2\baselineskip}{Dunhill style}
\scalebox{10}{Giant} |
Rules and Struts
[edit | edit source]Rules
[edit | edit source]The \rule
command in normal use produces a simple black box:
\rule[raise]{width}{thickness} |
The parameter thickness determines the height, whereas width determines the width of the produced rule. With the optional parameter raise, you can optionally raise or lower the produced rule above or below the baseline.
Here is an example (the thin lines are located at the baseline):
\rule{3mm}{.1pt}%
\rule[-1mm]{5mm}{1cm}%
\rule{3mm}{.1pt}%
\rule[1mm]{1cm}{5mm}%
\rule{3mm}{.1pt} |
This is useful for drawing vertical and horizontal lines.
Struts
[edit | edit source]A special case is a rule with no width but a certain height. In professional typesetting, this is called a strut. It is used to guarantee that an element on a page has a certain minimal height. You could use it in a tabular environment or in boxes to make sure a row has a certain minimum height.
In LaTeX a strut is defined as
\rule[-.3\baselineskip]{0pt}{\baselineskip} |
Stretched rules
[edit | edit source]LaTeX provides the \hrulefill
command, which work like a stretched horizontal space.
See the Lengths chapter.
Mathematics
[edit | edit source]One of the greatest motivating forces for Donald Knuth when he began developing the original TeX system was to create something that allowed simple construction of mathematical formulae, while it looking professional when printed. The fact that he succeeded was most probably why TeX (and later on, LaTeX) became so popular within the scientific community. Typesetting mathematics is one of LaTeX's greatest strengths. It is also a large topic due to the existence of so much mathematical notation.
If your document requires only a few simple mathematical formulas, plain LaTeX has most of the tools that you will ever need. If you are writing a scientific document that contains numerous complex formulas, the amsmath package[1] introduces several new commands that are more powerful and flexible than the ones provided by basic LaTeX. The mathtools package fixes some amsmath quirks and adds some useful settings, symbols, and environments to amsmath.[2] To use either package, include:
\usepackage{amsmath}
or
\usepackage{mathtools}
in the preamble of the document. The mathtools package loads the amsmath package and hence there is no need to \usepackage{amsmath}
in the preamble if mathtools is used.
Mathematics environments
[edit | edit source]LaTeX needs to know when the text is mathematical. This is because LaTeX typesets math notation differently from normal text. Therefore, special environments have been declared for this purpose. They can be distinguished into two categories depending on how they are presented:
- text — text formulas are displayed inline, that is, within the body of text where it is declared, for example, I can say that within this sentence.
- displayed — displayed formulas are on a line by themselves.
As math requires special environments, there are naturally the appropriate environment names you can use in the standard way. Unlike most other environments, however, there are some handy shorthands for declaring your formulas. The following table summarizes them:
Type | Inline (within text) formulas | Displayed equations | Displayed and automatically numbered equations |
---|---|---|---|
Environment | math
|
displaymath
|
equation
|
LaTeX shorthand | \(...\)
|
\[...\]
|
|
TeX shorthand | $...$
|
$$...$$
|
|
Comment | equation* (starred version) suppresses numbering, but requires amsmath
|
Suggestion: Using the $$...$$
should be avoided, as it may cause problems, particularly with the AMS-LaTeX macros. Furthermore, should a problem occur, the error messages may not be helpful.
The equation*
and displaymath
environments are functionally equivalent.
If you are typing text normally, you are said to be in text mode, but while you are typing within one of those mathematical environments, you are said to be in math mode, that has some differences compared to the text mode:
- Most spaces and line breaks do not have any significance, as all spaces are either derived logically from the mathematical expressions or have to be specified with special commands such as
\quad
- Empty lines are not allowed. Only one paragraph per formula.
- Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula (normal upright font with normal spacing), then you have to enter the text using dedicated commands.
Inserting "Displayed" maths inside blocks of text
[edit | edit source]In order for some operators, such as \lim
or \sum
, to be displayed correctly inside some math environments (read $......$
), it might be convenient to write the \displaystyle
class inside the environment. Doing so might cause the line to be taller, but will cause exponents and indices to be displayed correctly for some math operators. For example, the $\sum$
will print a smaller Σ and $\displaystyle \sum$
will print a bigger one , like in equations.[note 1] It is possible to force this behaviour for all math environments by declaring \everymath{\displaystyle}
in the preamble (i.e. before \begin{document}
).
Symbols
[edit | edit source]Mathematics has many symbols! The following is a set of symbols that can be accessed directly from the keyboard:
+ - = ! / ( ) [ ] < > | ' : *
Beyond those listed above, distinct commands must be issued in order to display the desired symbols. There are many examples such as Greek letters, set and relations symbols, arrows, binary operators, etc.
For example:
\forall x \in X, \quad \exists y \leq \epsilon |
|
Fortunately, there's a tool that can greatly simplify the search for the command for a specific symbol. Look for "Detexify" in the external links section below. Another option would be to look in "The Comprehensive LaTeX Symbol List" in the external links section below.
Greek letters
[edit | edit source]Greek letters are commonly used in mathematics, and they are very easy to type in math mode. You just have to type the name of the letter after a backslash: if the first letter is lowercase, you will get a lowercase Greek letter, if the first letter is uppercase (and only the first letter), then you will get an uppercase letter. Note that some uppercase Greek letters look like Latin ones, so they are not provided by LaTeX (e.g. uppercase Alpha and Beta are just "A" and "B", respectively). Lowercase epsilon, theta, kappa, phi, pi, rho, and sigma are provided in two different versions. The alternate, or variant, version is created by adding "var" before the name of the letter:
\alpha, \Alpha, \beta, \Beta, \gamma, \Gamma, \pi, \Pi, \phi, \varphi, \mu, \Phi |
|
Scroll down to #List of mathematical symbols for a complete list of Greek symbols.
Operators
[edit | edit source]An operator is a function that is written as a word: e.g. trigonometric functions (sin, cos, tan), logarithms and exponentials (log, exp), limits (lim), as well as trace and determinant (tr, det). LaTeX has many of these defined as commands:
\cos (2\theta) = \cos^2 \theta - \sin^2 \theta |
|
For certain operators such as limits, the subscript is placed underneath the operator:
\lim\limits_{x \to \infty} \exp(-x) = 0 |
|
For the modular operator there are two commands: \bmod
and \pmod
:
a \bmod b |
|
x \equiv a \pmod{b} |
|
To use operators that are not pre-defined, such as argmax, see custom operators
Powers and indices
[edit | edit source]Powers and indices are equivalent to superscripts and subscripts in normal text mode. The caret (^
; also known as the circumflex accent) character is used to raise something, and the underscore (_
) is for lowering. If an expression containing more than one character is raised or lowered, it should be grouped using curly braces ({
and }
).
k_{n+1} = n^2 + k_n^2 - k_{n-1} |
|
For powers with more than one digit, surround the power with {}.
x^{1.01} |
|
An underscore (_
) can be used with a vertical bar () to denote evaluation using subscript notation in mathematics:
f(n) = n^5 + 4n^2 + 2 |_{n=17} |
|
Fractions and Binomials
[edit | edit source]A fraction is created using the \frac{numerator}{denominator}
command (for those who need their memories refreshed, that's the top and bottom respectively!). Likewise, the binomial coefficient (a.k.a, the Choose function) may be written using the \binom
command:[note 1]
\frac{n!}{k!(n-k)!} = \binom{n}{k} |
|
You can embed fractions within fractions:
\frac{\frac{1}{x}+\frac{1}{y}}{y-z} |
|
Note that when appearing inside another fraction, or in inline text , a fraction is noticeably smaller than in displayed mathematics. The \tfrac
and \dfrac
commands[note 1] force the use of the respective styles, \textstyle
and \displaystyle
. Similarly, the \tbinom
and \dbinom
commands typeset the binomial coefficient.
For relatively simple fractions, especially within the text, it may be more aesthetically pleasing to use powers and indices instead:
^3/_7 |
|
If this looks a little "loose" (i.e., overspaced), a tightened version can be defined by inserting some negative space
%running fraction with slash - requires math mode.
\newcommand*\rfrac[2]{{}^{#1}\!/_{#2}}
\rfrac{3}{7} |
|
If you use them throughout the document, usage of xfrac package is recommended.
This package provides \sfrac
command to create slanted fractions. Usage:
Take $\sfrac{1}{2}$ cup of sugar, \dots
3\times\sfrac{1}{2}=1\sfrac{1}{2}
Take ${}^1/_2$ cup of sugar, \dots
3\times{}^1/_2=1{}^1/_2 |
If fractions are used as an exponent, curly braces have to be used around the \sfrac
command:
$x^\frac{1}{2}$ % no error $x^\sfrac{1}{2}$ % error $x^{\sfrac{1}{2}}$ % no error
$x^\frac{1}{2}$ % no error |
|
In some cases, using the package alone will result in errors about certain font shapes not being available. In that case, the lmodern and fix-cm packages need to be added as well.
Alternatively, the nicefrac package provides the \nicefrac
command, whose usage is similar to \sfrac
.
Continued fractions
[edit | edit source]Continued fractions should be written using \cfrac
command:[note 1]
\begin{equation}
x = a_0 + \cfrac{1}{a_1
+ \cfrac{1}{a_2
+ \cfrac{1}{a_3 + \cfrac{1}{a_4} } } }
\end{equation} |
|
Multiplication of two numbers
[edit | edit source]To make multiplication visually similar to a fraction, a nested array can be used. For example, multiplication of numbers written one below the other can be typeset as follows:
\begin{equation}
\frac{
\begin{array}[b]{r}
\left( x_1 x_2 \right)\\
\times \left( x'_1 x'_2 \right)
\end{array}
}{
\left( y_1y_2y_3y_4 \right)
}
\end{equation} |
|
Roots
[edit | edit source]The \sqrt
command creates a square root surrounding an expression. It accepts an optional argument specified in square brackets ([
and ]
) to change magnitude:
\sqrt{\frac{a}{b}} |
|
\sqrt[n]{1+x+x^2+x^3+\dots+x^n} |
|
Some people prefer writing the square root "closing" it over its content. This method arguably makes it more clear what is in the scope of the root sign. This habit is not normally used while writing with the computer, but if you still want to change the output of the square root, LaTeX gives you this possibility. Just add the following code in the preamble of your document:
% New definition of square root:
% it renames \sqrt as \oldsqrt
\let\oldsqrt\sqrt
% it defines the new \sqrt in terms of the old one
\def\sqrt{\mathpalette\DHLhksqrt}
\def\DHLhksqrt#1#2{%
\setbox0=\hbox{$#1\oldsqrt{#2\,}$}\dimen0=\ht0
\advance\dimen0-0.2\ht0
\setbox2=\hbox{\vrule height\ht0 depth -\dimen0}%
{\box0\lower0.4pt\box2}} |
This TeX code first renames the \sqrt
command as \oldsqrt
, then redefines \sqrt
in terms of the old one, adding something more. The new square root can be seen in the picture on the left, compared to the old one on the right. Unfortunately this code won't work if you want to use multiple roots: if you try to write as \sqrt[b]{a}
after you used the code above, you'll just get a wrong output. In other words, you can redefine the square root this way only if you are not going to use multiple roots in the whole document.
An alternative piece of TeX code that does allow multiple roots is
\usepackage{letltxmacro}
\makeatletter
\let\oldr@@t\r@@t
\def\r@@t#1#2{%
\setbox0=\hbox{$\oldr@@t#1{#2\,}$}\dimen0=\ht0
\advance\dimen0-0.2\ht0
\setbox2=\hbox{\vrule height\ht0 depth -\dimen0}%
{\box0\lower0.4pt\box2}}
\LetLtxMacro{\oldsqrt}{\sqrt}
\renewcommand*{\sqrt}[2][\ ]{\oldsqrt[#1]{#2} }
\makeatother
$\sqrt[a]{b} \quad \oldsqrt[a]{b}$ |
However, this requires the \usepackage{letltxmacro}
package.
Sums and integrals
[edit | edit source]The \sum
and \int
commands insert the sum and integral symbols respectively, with limits specified using the caret (^
) and underscore (_
). The typical notation for sums is:
\sum_{i=1}^{10} t_i |
|
or
\displaystyle\sum_{i=1}^{10} t_i |
|
The limits for the integrals follow the same notation. It's also important to represent the integration variables with an upright d, which in math mode is obtained through the \mathrm{} command, and with a small space separating it from the integrand, which is attained with the \, command.
\int_0^\infty \mathrm{e}^{-x}\,\mathrm{d}x |
|
There are many other "big" commands which operate in a similar manner:
\sum |
\prod |
\coprod |
|||||
\bigoplus |
\bigotimes |
\bigodot |
|||||
\bigcup |
\bigcap |
\biguplus |
|||||
\bigsqcup |
\bigvee |
\bigwedge |
|||||
\int |
\oint |
\iint [note 1] |
|||||
\iiint [note 1] |
\iiiint [note 1] |
\idotsint [note 1] |
For more integral symbols, including those not included by default in the Computer Modern font, try the esint package.
The \substack
command[note 1] allows the use of \\
to write the limits over multiple lines:
\sum_{\substack{
0<i<m \\
0<j<n
}}
P(i,j) |
|
If you want the limits of an integral to be specified above and below the symbol (like the sum), use the \limits
command:
\int\limits_a^b |
|
However, if you want this to apply to all integrals, it is preferable to specify the intlimits option when loading the amsmath package:
\usepackage[intlimits]{amsmath} |
Subscripts and superscripts in other contexts, as well as other parameters to amsmath package related to them, are described in Advanced Mathematics chapter.
For bigger integrals, you may use personal declarations, or the bigints package [3].
Brackets, braces and delimiters
[edit | edit source]How to use braces in multi line equations is described in the Advanced Mathematics chapter.
The use of delimiters such as brackets soon becomes important when dealing with anything but the most trivial equations. Without them, formulas can become ambiguous. Also, special types of mathematical structures, such as matrices, typically rely on delimiters to enclose them.
There are a variety of delimiters available for use in LaTeX:
( a ), [ b ], \{ c \}, | d |, \| e \|,
\langle f \rangle, \lfloor g \rfloor,
\lceil h \rceil, \ulcorner i \urcorner,
/ j \backslash |
|
where \lbrack
and \rbrack
may be used in place of [ and ].
Automatic sizing
[edit | edit source]Very often, mathematical features will differ in size, in which case the delimiters surrounding the expression should vary accordingly. This can be done automatically using the \left
, \right
, and \middle
commands. Any of the previous delimiters may be used in combination with these:
\left(\frac{x^2}{y^3}\right) |
|
P\left(A=2\middle|\frac{A^2}{B}>4\right) |
Curly braces are defined differently by using \left\{
and \right\}
,
\left\{\frac{x^2}{y^3}\right\} |
|
If a delimiter on only one side of an expression is required, then an invisible delimiter on the other side may be denoted using a period (.
).
\left.\frac{x^3}{3}\right|_0^1 |
|
Manual sizing
[edit | edit source]In certain cases, the sizing produced by the \left
and \right
commands may not be desirable, or you may simply want finer control over the delimiter sizes. In this case, the \big
, \Big
, \bigg
and \Bigg
modifier commands may be used:
( \big( \Big( \bigg( \Bigg( |
|
These commands are primarily useful when dealing with nested delimiters. For example, when typesetting
\frac{\mathrm d}{\mathrm d x} \left( k g(x) \right) |
|
we notice that the \left
and \right
commands produce the same size delimiters as those nested within it. This can be difficult to read. To fix this, we write
\frac{\mathrm d}{\mathrm d x} \big( k g(x) \big) |
|
Manual sizing can also be useful when an equation is too large, trails off the end of the page, and must be separated into two lines using an align command. Although the commands \left.
and \right.
can be used to balance the delimiters on each line, this may lead to wrong delimiter sizes. Furthermore, manual sizing can be used to avoid overly large delimiters — if an \underbrace
or a similar command appears between the delimiters.
Matrices and arrays
[edit | edit source]A basic matrix may be created using the matrix environment[note 1]: in common with other table-like structures, entries are specified by row, with columns separated using an ampersand (&
) and new rows separated with a double backslash (\\
)
\[
\begin{matrix}
a & b & c \\
d & e & f \\
g & h & i
\end{matrix}
\] |
|
To specify alignment of columns in the table, use starred version[note 2]:
\begin{matrix}
-1 & 3 \\
2 & -4
\end{matrix}
=
\begin{matrix*}[r]
-1 & 3 \\
2 & -4
\end{matrix*} |
|
The alignment by default is c, but it can be any column type valid in array environment.
However matrices are usually enclosed in delimiters of some kind, and while it is possible to use the \left
and \right
commands, there are various other predefined environments which automatically include delimiters:
Environment name | Surrounding delimiter | Notes |
---|---|---|
pmatrix[note 1] | centers columns by default | |
pmatrix*[note 2] | allows to specify alignment of columns in optional parameter | |
bmatrix[note 1] | centers columns by default | |
bmatrix*[note 2] | allows to specify alignment of columns in optional parameter | |
Bmatrix[note 1] | centers columns by default | |
Bmatrix*[note 2] | allows to specify alignment of columns in optional parameter | |
vmatrix[note 1] | centers columns by default | |
vmatrix*[note 2] | allows to specify alignment of columns in optional parameter | |
Vmatrix[note 1] | centers columns by default | |
Vmatrix*[note 2] | allows to specify alignment of columns in optional parameter |
When writing down arbitrary sized matrices, it is common to use horizontal, vertical and diagonal triplets of dots (known as ellipses) to fill in certain columns and rows. These can be specified using the \cdots
, \vdots
and \ddots
respectively:
A_{m,n} =
\begin{pmatrix}
a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\
a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\
\vdots & \vdots & \ddots & \vdots \\
a_{m,1} & a_{m,2} & \cdots & a_{m,n}
\end{pmatrix} |
|
In some cases, you may want to have finer control of the alignment within each column, or to insert lines between columns or rows. This can be achieved using the array environment, which is essentially a math-mode version of the tabular
environment, which requires that the columns be pre-specified:
\begin{array}{c|c}
1 & 2 \\
\hline
3 & 4
\end{array} |
|
You may see that the AMS matrix class of environments doesn't leave enough space when used together with fractions resulting in output similar to this:
To counteract this problem, add additional leading space with the optional parameter to the \\
command:
M = \begin{bmatrix}
\frac{5}{6} & \frac{1}{6} & 0 \\[0.3em]
\frac{5}{6} & 0 & \frac{1}{6} \\[0.3em]
0 & \frac{5}{6} & \frac{1}{6}
\end{bmatrix} |
|
If you need "border" or "indexes" on your matrix, plain TeX provides the macro \bordermatrix
M = \bordermatrix{~ & x & y \cr
A & 1 & 0 \cr
B & 0 & 1 \cr} |
Matrices in running text
[edit | edit source]To insert a small matrix without increasing leading in the line containing it, use smallmatrix environment:
A matrix in text must be set smaller:
$\bigl(\begin{smallmatrix}
a&b \\ c&d
\end{smallmatrix} \bigr)$
to not increase leading in a portion of text. |
Adding text to equations
[edit | edit source]The math environment differs from the text environment in the representation of text. Here is an example of trying to represent text within the math environment:
50 apples \times 100 apples = lots of apples^2 |
|
There are two noticeable problems: there are no spaces between words or numbers, and the letters are italicized and more spaced out than normal. Both issues are simply artifacts of the maths mode, in that it treats it as a mathematical expression: spaces are ignored (LaTeX spaces mathematics according to its own rules), and each character is a separate element (so are not positioned as closely as normal text).
There are a number of ways that text can be added properly. The typical way is to wrap the text with the \text{...}
command[note 1] (a similar command is \mbox{...}
, though this causes problems with subscripts, and has a less descriptive name). Let's see what happens when the above equation code is adapted:
50 \text{apples} \times 100 \text{apples}
= \text{lots of apples}^2 |
|
The text looks better. However, there are no gaps between the numbers and the words. Unfortunately, you are required to explicitly add these. There are many ways to add spaces between math elements, but for the sake of simplicity we may simply insert space characters into the \text
commands.
50 \text{ apples} \times 100 \text{ apples}
= \text{lots of apples}^2 |
|
Formatted text
[edit | edit source]Using the \text
is fine and gets the basic result. Yet, there is an alternative that offers a little more flexibility. You may recall the introduction of font formatting commands, such as \textrm
, \textit
, \textbf
, etc. These commands format the argument accordingly, e.g., \textbf{bold text}
gives bold text. These commands are equally valid within a maths environment to include text. The added benefit here is that you can have better control over the font formatting, rather than the standard text achieved with \text
.
50 \textrm{ apples} \times 100
\textbf{ apples} = \textit{lots of apples}^2 |
|
Formatting mathematics symbols
[edit | edit source]- See also: w:Mathematical Alphanumeric Symbols, w:Help:Displaying a formula#Alphabets and typefaces and w:Wikipedia:LaTeX symbols#Fonts
We can now format text; what about formatting mathematical expressions? There are a set of formatting commands very similar to the font formatting ones just used, except that they are specifically aimed at text in math mode (requires amsfonts)
LaTeX command | Sample | Description | Common use |
---|---|---|---|
\mathnormal{…} (or simply omit any command) |
The default math font | Most mathematical notation | |
\mathrm{…}
|
This is the default or normal font, unitalicised | Units of measurement, one word functions | |
\mathit{…}
|
Italicised font | Multi-letter function or variable names. Compared to \mathnormal , words are spaced more naturally and numbers are italicized as well.
| |
\mathbf{…}
|
Bold font | Vectors | |
\mathsf{…}
|
Sans-serif | Categories | |
\mathtt{…}
|
Monospace (fixed-width) font | ||
\mathfrak{…} (requires the amsfonts or amssymb package[note 3]) |
Fraktur | Almost canonical font for Lie algebras, ideals in ring theory | |
\mathcal{…}
|
Calligraphy (uppercase only[note 3]) | Often used for sheaves/schemes and categories, used to denote cryptological concepts like an alphabet of definition (), message space (), ciphertext space () and key space (); Kleene's ; naming convention in description logic; Laplace transform () and Fourier transform () | |
\mathbb{…} (requires the amsfonts or amssymb package[note 3]) |
Blackboard bold (uppercase only[note 3]) | Used to denote special sets (e.g. real numbers) | |
\mathscr{…} (requires the mathrsfs package[note 3]) |
Script (uppercase only[note 3]) | An alternative font for categories and sheaves. |
These formatting commands can be wrapped around the entire equation, and not just on the textual elements: they only format letters, numbers, and uppercase Greek, and other math commands are unaffected.
To bold lowercase Greek or other symbols use the \boldsymbol
command[note 1]; this will only work if there exists a bold version of the symbol in the current font. As a last resort there is the \pmb
command[note 1] (poor man's bold): this prints multiple versions of the character slightly offset against each other.
\boldsymbol{\beta} = (\beta_1,\beta_2,\dotsc,\beta_n) |
|
To change the size of the fonts in math mode, see Changing font size.
Accents
[edit | edit source]So what to do when you run out of symbols and fonts? Well, the next step is to use accents:
a' or a^{\prime} |
a'' |
||
\hat{a} |
\bar{a} |
||
\grave{a} |
\acute{a} |
||
\dot{a} |
\ddot{a} |
||
\not{a} |
\mathring{a} |
å | |
\overrightarrow{AB} |
\overleftarrow{AB} |
||
a''' |
a'''' |
||
\overline{aaa} |
\check{a} |
||
\breve{a} |
\vec{a} |
||
\dddot{a} [note 1] |
\ddddot{a} [note 1] |
||
\widehat{AAA} |
\widetilde{AAA} |
||
\stackrel\frown{AAA} |
|||
\tilde{a} |
\underline{a} |
Color
[edit | edit source]The package xcolor, described in Colors, allows us to add color to our equations. For example,
k = {\color{red}x} \mathbin{\color{blue}-} 2 |
|
The only problem is that this disrupts the default LaTeX formatting around the -
operator. To fix this, we enclose it in a \mathbin
environment, since -
is a binary operator. This process is described here.
Plus and minus signs
[edit | edit source]LaTeX deals with the + and − signs in two possible ways. The most common is as a binary operator. When two maths elements appear on either side of the sign, it is assumed to be a binary operator, and as such, allocates some space to either side of the sign. The alternative way is a sign designation. This is when you state whether a mathematical quantity is either positive or negative. This is common for the latter, as in math, such elements are assumed to be positive unless a − is prefixed to it. In this instance, you want the sign to appear close to the appropriate element to show their association. If you put a + or a − with nothing before it but you want it to be handled like a binary operator you can add an invisible character before the operator using {}
. This can be useful if you are writing multiple-line formulas, and a new line could start with a − or +, for example, then you can fix some strange alignments adding the invisible character where necessary.
A plus-minus sign is written as:
\pm |
|
Similarly, there exists also a minus-plus sign:
\mp |
|
Controlling horizontal spacing
[edit | edit source]LaTeX is obviously pretty good at typesetting maths—it was one of the chief aims of the core TeX system that LaTeX extends. However, it can't always be relied upon to accurately interpret formulas in the way you did. It has to make certain assumptions when there are ambiguous expressions. The result tends to be slightly incorrect horizontal spacing. In these events, the output is still satisfactory, yet any perfectionists will no doubt wish to fine-tune their formulas to ensure spacing is correct. These are generally very subtle adjustments.
There are other occasions where LaTeX has done its job correctly, but you just want to add some space, maybe to add a comment of some kind. For example, in the following equation, it is preferable to ensure there is a decent amount of space between the maths and the text.
\[ f(n) =
\begin{cases}
n/2 & \quad \text{if } n \text{ is even}\\
-(n+1)/2 & \quad \text{if } n \text{ is odd}
\end{cases}
\] |
|
This code produces errors with Miktex 2.9 and does not yield the results seen on the right. Use \mathrm instead of just \text.
(Note that this particular example can be expressed in more elegant code by the cases construct provided by the amsmath package described in Advanced Mathematics chapter.)
LaTeX has defined two commands that can be used anywhere in documents (not just maths) to insert some horizontal space. They are \quad
and \qquad
A \quad
is a space equal to the current font size. So, if you are using an 11pt font, then the space provided by \quad
will also be 11pt (horizontally, of course.) The \qquad
gives twice that amount. As you can see from the code from the above example, \quad
s were used to add some separation between the maths and the text.
OK, so back to the fine tuning as mentioned at the beginning of the document. A good example would be displaying the simple equation for the indefinite integral of y with respect to x:
If you were to try this, you may write:
\int y \mathrm{d}x |
|
However, this doesn't give the correct result. LaTeX doesn't respect the white-space left in the code to signify that the y and the dx are independent entities. Instead, it lumps them altogether. A \quad
would clearly be overkill in this situation—what is needed are some small spaces to be utilized in this type of instance, and that's what LaTeX provides:
Command | Description | Size |
---|---|---|
\,
|
small space | 3/18 of a quad |
\:
|
medium space | 4/18 of a quad |
\;
|
large space | 5/18 of a quad |
\!
|
negative space | -3/18 of a quad |
NB you can use more than one command in a sequence to achieve a greater space if necessary.
So, to rectify the current problem:
\int y\, \mathrm{d}x |
|
\int y\: \mathrm{d}x |
|
\int y\; \mathrm{d}x |
|
The negative space may seem like an odd thing to use, however, it wouldn't be there if it didn't have some use! Take the following example:
\left(
\begin{array}{c}
n \\
r
\end{array}
\right) = \frac{n!}{r!(n-r)!} |
|
The matrix-like expression for representing binomial coefficients is too padded. There is too much space between the brackets and the actual contents within. This can easily be corrected by adding a few negative spaces after the left bracket and before the right bracket.
\left(\!
\begin{array}{c}
n \\
r
\end{array}
\!\right) = \frac{n!}{r!(n-r)!} |
|
In any case, adding some spaces manually should be avoided whenever possible: it makes the source code more complex and it's against the basic principles of a What You See is What You Mean approach. The best thing to do is to define some commands using all the spaces you want and then, when you use your command, you don't have to add any other space. Later, if you change your mind about the length of the horizontal space, you can easily change it modifying only the command you defined before. Let us use an example: you want the d of a dx in an integral to be in roman font and a small space away from the rest. If you want to type an integral like \int x \, \mathrm{d} x
, you can define a command like this:
\newcommand{\dd}{\mathop{}\,\mathrm{d}} |
in the preamble of your document. We have chosen \dd
just because it reminds the "d" it replaces and it is fast to type. Doing so, the code for your integral becomes \int x \dd x
. Now, whenever you write an integral, you just have to use the \dd
instead of the "d", and all your integrals will have the same style. If you change your mind, you just have to change the definition in the preamble, and all your integrals will be changed accordingly.
Manually Specifying Formula Style
[edit | edit source]To manually display a fragment of a formula using text style, surround the fragment with curly braces and prefix the fragment with \textstyle
. The braces are required because the \textstyle
macro changes the state of the renderer, rendering all subsequent mathematics in text style. The braces limit this change of state to just the fragment enclosed within. For example, to use text style for just the summation symbol in a sum, one would enter
\begin{equation}
C^i_j = {\textstyle \sum_k} A^i_k B^k_j
\end{equation} |
The same thing as a command would look like this:
\newcommand{\tsum}[1]{{\textstyle \sum_{#1}}} |
Note the extra braces. Just one set around the expression won't be enough. That would cause all math after \tsum k
to be displayed using text style.
To display part of a formula using display style, do the same thing, but use \displaystyle
instead.
Advanced Mathematics: AMS Math package
[edit | edit source]The AMS (American Mathematical Society) mathematics package is a powerful package that creates a higher layer of abstraction over mathematical LaTeX language; if you use it it will make your life easier. Some commands amsmath introduces will make other plain LaTeX commands obsolete: in order to keep consistency in the final output you'd better use amsmath commands whenever possible. If you do so, you will get an elegant output without worrying about alignment and other details, keeping your source code readable. If you want to use it, you have to add this in the preamble:
\usepackage{amsmath} |
Introducing dots in formulas
[edit | edit source]amsmath defines also the \dots
command, that is a generalization of the existing \ldots
. You can use \dots
in both text and math mode and LaTeX will replace it with three dots "…" but it will decide according to the context whether to put it on the bottom (like \ldots
) or centered (like \cdots
).
Dots
[edit | edit source]LaTeX gives you several commands to insert dots (ellipses) in your formulae. This can be particularly useful if you have to type big matrices omitting elements. First of all, here are the main dots-related commands LaTeX provides:
Code | Output | Comment |
---|---|---|
\dots |
generic dots (ellipsis), to be used in text (outside formulae as well). It automatically manages whitespaces before and after itself according to the context, it's a higher level command. | |
\ldots |
the output is similar to the previous one, but there is no automatic whitespace management; it works at a lower level. | |
\cdots |
These dots are centered relative to the height of a letter. There is also the binary multiplication operator, \cdot , mentioned below.
| |
\vdots |
vertical dots | |
\ddots |
diagonal dots | |
\iddots |
inverse diagonal dots (requires the mathdots package) | |
\hdotsfor{n} |
to be used in matrices, it creates a row of dots spanning n columns. |
Instead of using \ldots
and \cdots
, you should use the semantically oriented commands. It makes it possible to adapt your document to different conventions on the fly, in case (for example) you have to submit it to a publisher who insists on following house tradition in this respect. The default treatment for the various kinds follows American Mathematical Society conventions.
Write an equation with the align environment
[edit | edit source]How to write an equation with the align environment with the amsmath package is described in Advanced Mathematics.
List of mathematical symbols
[edit | edit source]All the pre-defined mathematical symbols from the \TeX\ package are listed below. More symbols are available from extra packages.
Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
<
|
>
|
=
|
\parallel
|
\nparallel
| |||||||||
\leq
|
\geq
|
\doteq
|
\asymp
|
\bowtie
| |||||||||
\ll
|
\gg
|
\equiv
|
\vdash
|
\dashv
| |||||||||
\subset
|
\supset
|
\approx
|
\in
|
\ni
| |||||||||
\subseteq
|
\supseteq
|
\cong
|
\smile
|
\frown
| |||||||||
\nsubseteq
|
\nsupseteq
|
\simeq
|
\models
|
\notin
| |||||||||
\sqsubset
|
\sqsupset
|
\sim
|
\perp
|
\mid
| |||||||||
\sqsubseteq
|
\sqsupseteq
|
\propto
|
\prec
|
\succ
| |||||||||
\preceq
|
\succeq
|
\neq
|
\sphericalangle
|
\measuredangle
| |||||||||
\therefore
|
\because
|
Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | |||
---|---|---|---|---|---|---|---|---|---|---|
\pm
|
\cap
|
\diamond
|
\oplus
| |||||||
\mp
|
\cup
|
\bigtriangleup
|
\ominus
| |||||||
\times
|
\uplus
|
\bigtriangledown
|
\otimes
| |||||||
\div
|
\sqcap
|
\triangleleft
|
\oslash
| |||||||
\ast
|
\sqcup
|
\triangleright
|
\odot
| |||||||
\star
|
\vee
|
\bigcirc
|
\circ
| |||||||
\dagger
|
\wedge
|
\bullet
|
\setminus
| |||||||
\ddagger
|
\cdot
|
\wr
|
\amalg
|
Symbol | Script | Symbol | Script | |
---|---|---|---|---|
\exists
|
\rightarrow or \to
| |||
\nexists
|
\leftarrow or \gets
| |||
\forall
|
\mapsto
| |||
\neg
|
\implies
| |||
\cap
|
||||
\cup
|
||||
\subset
|
⟸ | \impliedby
| ||
\supset
|
\Rightarrow or \implies
| |||
\in
|
\leftrightarrow
| |||
\notin
|
\iff
| |||
\ni
|
\Leftrightarrow (preferred for equivalence (iff))
| |||
\land
|
\top
| |||
\lor
|
\bot
| |||
\angle
|
and | \emptyset and \varnothing [27]
| ||
\rightleftharpoons
|
Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | |||
---|---|---|---|---|---|---|---|---|---|---|
| or \mid (difference in spacing)
|
\|
|
/
|
\backslash
| |||||||
\{
|
\}
|
\langle
|
\rangle
| |||||||
\uparrow
|
\Uparrow
|
\lceil
|
\rceil
| |||||||
\downarrow
|
\Downarrow
|
\lfloor
|
\rfloor
|
Note: To use the Greek Letters in LaTeX that have the same appearance in the Latin alphabet, just use Latin: e.g., A instead of Alpha, B instead of Beta, etc.
Symbol | Script | Symbol | Script | |
---|---|---|---|---|
and | A and \alpha
|
and | N and \nu
| |
and | B and \beta
|
and | \Xi and \xi
| |
and | \Gamma and \gamma
|
and | O and o
| |
and | \Delta and \delta
|
, and | \Pi , \pi and \varpi
| |
, and | E , \epsilon and \varepsilon
|
, and | P , \rho and \varrho
| |
and | Z and \zeta
|
, and | \Sigma , \sigma and \varsigma
| |
and | H and \eta
|
and | T and \tau
| |
, and | \Theta , \theta and \vartheta
|
, and | Y , \Upsilon and \upsilon
| |
and | I and \iota
|
, , and | \Phi , \phi and \varphi
| |
, and | K , \kappa and \varkappa
|
and | X and \chi
| |
and | \Lambda and \lambda
|
and | \Psi and \psi
| |
and | M and \mu
|
and | \Omega and \omega
|
Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
\partial
|
\imath
|
\Re
|
\nabla
|
\aleph
| |||||||||
\eth
|
\jmath
|
\Im
|
\Box
|
\beth
| |||||||||
\hbar
|
\ell
|
\wp
|
\infty
|
\gimel
|
^ Not predefined in LATEX 2. Use one of the packages latexsym, amsfonts, amssymb, txfonts, pxfonts, or wasysym
Symbol | Script | Symbol | Script | Symbol | Script | Symbol | Script | |||
---|---|---|---|---|---|---|---|---|---|---|
\sin
|
\arcsin
|
\sinh
|
\sec
| |||||||
\cos
|
\arccos
|
\cosh
|
\csc
| |||||||
\tan
|
\arctan
|
\tanh
|
||||||||
\cot
|
\arccot
|
\coth
|
If LaTeX does not include a command for the mathematical operator you want to use, for example \cis
(cosine plus i times sine), add to your preamble:
\DeclareMathOperator\cis{cis}
You can then use \cis
in the document just like \cos
or any other mathematical operator.
Summary
[edit | edit source]As you begin to see, typesetting math can be tricky at times. However, because LaTeX provides so much control, you can get professional quality mathematics typesetting with relatively little effort (once you've had a bit of practice, of course!). It is possible to elaborate further on the nitty-gritty of mathematics because the possibilities seem endless. However, with this tutorial, you should be able to get along with it sufficiently.
References
[edit | edit source]Notes
[edit | edit source]- ↑ a b c d e f g h i j k l m n o p q r s t requires the amsmath package
- ↑ a b c d e f requires the mathtools package
- ↑ a b c d e f The mathalpha package allows for specifying a broader variety of fonts to be used in the
\mathfrak{}
,\mathbb{}
,\mathcal{}
and\mathscr{}
commands. For example, the command\usepackage[bb=pazo]{mathalpha}
makes it so\mathbb{}
uses the "pazo" font. mathalpha's documentation gives a comparison of the different font options; some have lowercase letters, Greek letters or numerals where the default does not.
Further reading
[edit | edit source]- meta:Help:Displaying a formula: Wikimedia uses a subset of LaTeX commands.
External links
[edit | edit source]- detexify: applet for looking up LaTeX symbols by drawing them
- amsmath documentation
- LaTeX - The Student Room
- The Comprehensive LaTeX Symbol List
- Comprehensive List of Mathematical Symbols
Advanced Mathematics
[edit | edit source]This page outlines some more advanced uses of mathematics markup using LaTeX. In particular it makes heavy use of the AMS-LaTeX packages supplied by the American Mathematical Society.
Equation numbering
[edit | edit source]The equation
environment automatically numbers your equation:
\begin{equation}
f(x)=(x+a)(x+b)
\end{equation} |
|
You can also use the \label
and \ref
(or \eqref
from the amsmath package) commands to label and reference equations, respectively. For equation number 1, \ref
results in and \eqref
results in :
\begin{equation} \label{eq:someequation}
6^2 - 5 = 36-5 = 31
\end{equation}
this references equation \ref{eq:someequation}. |
|
\begin{equation} \label{eq:erl}
a = bq + r
\end{equation}
where \eqref{eq:erl} is true if $a$ and $b$ are integers with $b \neq c$. |
|
Further information is provided in the labels and cross-referencing chapter.
To have the enumeration follow from your section or subsection heading, you must use the amsmath package or use AMS class documents. Then enter
\numberwithin{equation}{section} |
to the preamble to get enumeration at the section level or
\numberwithin{equation}{subsection} |
to have the enumeration go to the subsection level.
\documentclass[12pt]{article}
\usepackage{amsmath}
\numberwithin{equation}{subsection}
\begin{document}
\section{First Section}
\subsection{A subsection}
\begin{equation}
L' = {L}{\sqrt{1-\frac{v^2}{c^2}}}
\end{equation}
\end{document} |
|
If the style you follow requires putting dots after ordinals (as it is required at least in Polish typography), the \numberwithin{equation}{subsection}
command in the preamble will result in the equation number in the above example being rendered as follows: (1.1.1).
To remove the duplicate dot, add the following command immediately after
\numberwithin{equation}{section}
:
\renewcommand{\theequation}{\thesection\arabic{equation}} |
For a numbering scheme using \numberwithin{equation}{subsection}
, use:
\renewcommand{\theequation}{\thesubsection\arabic{equation}} |
in the preamble of the document.
Note: Although it may look like the \renewcommand
works by itself, it won't reset the equation number with each new section. It must be used together with manual equation number resetting after each new section beginning, or with the much cleaner \numberwithin
.
Subordinate equation numbering
[edit | edit source]To number subordinate equations in a numbered equation environment, place the part of document containing them in a subequations environment:
\begin{subequations}
\label{eq:Maxwell}
Maxwell's equations:
\begin{align}
B'&=-\nabla \times E, \label{eq:MaxB} \\
E'&=\nabla \times B - 4\pi j, \label{eq:MaxE}
\end{align}
\end{subequations} |
|
Referencing subordinate equations can be done using either of two methods: adding a label after the \begin{subequations}
command, viz. \label{eq:Maxwell}
, which will reference the main equation (1.1 above), or adding a label at the end of each line, before the \\
command, which will reference the sub-equation (1.1a or 1.1b above). As shown, it is possible to add both labels in case both types of references are needed.
/Override_subsystem=/index
Vertically aligning displayed mathematics
[edit | edit source]A problem often encountered with displayed environments (displaymath and equation) is the lack of any ability to span multiple lines. While it is possible to define lines individually, these will not be aligned.
Above and below
[edit | edit source]The \overset
and \underset
commands[1] typeset symbols above and below expressions.
Without AMS-TeX the same result of \overset
can be obtained with \stackrel
.
This can be particularly useful for creating new binary relations:
\[
A \overset{!}{=} B; A \stackrel{!}{=} B
\] |
|
or to show usage of L'Hôpital's rule:
\[
\lim_{x\to 0}{\frac{e^x-1}{2x}}
\overset{\left[\frac{0}{0}\right]}{\underset{\mathrm{H}}{=}}
\lim_{x\to 0}{\frac{e^x}{2}}={\frac{1}{2}}
\] |
|
It is convenient to define a new operator that will set the equals sign with H and the provided fraction:
\newcommand{\Heq}[1]{\overset{\left[#1\right]}{\underset{\mathrm{H}}{=}}} |
which reduces the above example to:
\[
\lim_{x\to 0}{\frac{e^x-1}{2x}}
\Heq{\frac{0}{0}}
\lim_{x\to 0}{\frac{e^x}{2}}={\frac{1}{2}}
\] |
If the purpose is to make comments on particular parts of an equation, the \overbrace
and \underbrace
commands may be more useful. However, they have a different syntax (and can be aligned with the \vphantom
command):
\[
z = \overbrace{
\underbrace{x}_\text{real} + i
\underbrace{y}_\text{imaginary}
}^\text{complex number}
\] |
|
Sometimes the comments are longer than the formula being commented on, which can cause spacing problems. These can be removed using the \mathclap
command[2]:
\[
y = a + f(\underbrace{b x}_{
\ge 0 \text{ by assumption}})
= a + f(\underbrace{b x}_{
\mathclap{\ge 0 \text{ by assumption}}})
\] |
Alternatively, to use brackets instead of braces use \underbracket
and \overbracket
commands[2]:
\[
z = \overbracket[3pt]{
\underbracket{x}_{\text{real}} +
\underbracket[0.5pt][7pt]{iy}_{\text{imaginary}}
}^{\text{complex number}}
\] |
The optional arguments set the rule thickness and bracket height respectively:
\underbracket[rule thickness][bracket height]{argument}_{text below} |
The \xleftarrow
and \xrightarrow
commands[1] produce arrows which extend to the length of the text. Yet again, the syntax is different: the optional argument (using [
and ]
) specifies the subscript, and the mandatory argument (using {
and }
) specifies the superscript (which can be left empty by inserting a blank space).
\[
A \xleftarrow{\text{this way}} B
\xrightarrow[\text{or that way}]{ } C
\] |
|
For more extensible arrows, you must use the mathtools package:
\begin{gather}
a \xleftrightarrow[under]{over} b\\
%
A \xLeftarrow[under]{over} B\\
%
B \xRightarrow[under]{over} C\\
%
C \xLeftrightarrow[under]{over} D\\
%
D \xhookleftarrow[under]{over} E\\
%
E \xhookrightarrow[under]{over} F\\
%
F \xmapsto[under]{over} G\\
\end{gather} |
and for harpoons:
\begin{gather}
H \xrightharpoondown[under]{over} I\\
%
I \xrightharpoonup[under]{over} J\\
%
J \xleftharpoondown[under]{over} K\\
%
K \xleftharpoonup[under]{over} L\\
%
L \xrightleftharpoons[under]{over} M\\
%
M \xleftrightharpoons[under]{over} N
\end{gather} |
align and align*
[edit | edit source]The align and align* environments, available through the amsmath package, are used for arranging equations of multiple lines. As with matrices and tables, \\
specifies a line break, and &
is used to indicate the point at which the lines should be aligned.
The align* environment is used like the displaymath or equation* environment:
\begin{align*}
f(x) &= (x+a)(x+b) \\
&= x^2 + (a+b)x + ab
\end{align*} |
|
Note that the align environment must not be nested inside an equation (or similar) environment. Instead, align is a replacement for such environments; the contents inside an align are automatically placed in math mode.
align* suppresses numbering. To force numbering on a specific line, use the \tag{...}
command before the line break.
align is similar, but automatically numbers each line like the equation environment. Individual lines may be referred to by placing a \label{...}
before the line break. The \nonumber
or \notag
command can be used to suppress the number for a given line:
\begin{align}
f(x) &= x^4 + 7x^3 + 2x^2 \nonumber \\
&\qquad {} + 10x + 12
\end{align} |
|
Notice that we've added some indenting on the second line. Also, we need to insert the double braces ({}
) before the + sign, otherwise latex won't create the correct spacing after the + sign. The reason for this is that without the braces, latex interprets the + sign as a unary operator, instead of the binary operator that it really is.
More complicated alignments are possible, with additional &
's on a single line specifying multiple "equation columns", each of which is aligned. The following example illustrates the alignment rule of align*:
\begin{align*}
f(x) &= a x^2+b x +c & g(x) &= d x^3 \\
f'(x) &= 2 a x +b & g'(x) &= 3 d x^2
\end{align*} |
|
Braces spanning multiple lines
[edit | edit source]If you want a brace to continue across a new line, do the following:
\begin{align}
f(x) &= \pi \left\{ x^4 + 7x^3 + 2x^2 \right.\nonumber\\
&\qquad \left. {} + 10x + 12 \right\}
\end{align} |
|
In this construction, the sizes of the left and right braces are not automatically equal, in spite of the use of \left\{
and \right\}
. This is because each line is typeset as a completely separate equation —notice the use of \right.
and \left.
so there are no unpaired \left
and \right
commands within a line (these aren't needed if the formula is on one line). You can control the size of the braces manually with the \big
, \Big
, \bigg
, and \Bigg
commands.
Alternatively, the height of the taller equation can be replicated in the other using the \vphantom
command:
\begin{align}
A &= \left(\int_t XXX \right.\nonumber\\
&\qquad \left.\vphantom{\int_t} YYY \dots \right)
\end{align} |
|
Using aligned braces for piecewise functions
[edit | edit source]You can also use \left\{
and \right.
to typeset piecewise functions:
\[f(x) = \left\{
\begin{array}{lr}
x^2 & : x < 0\\
x^3 & : x \ge 0
\end{array}
\right.
\] |
|
The cases environment
[edit | edit source]The cases environment[1] allows the writing of piecewise functions:
\[
u(x) =
\begin{cases}
\exp{x} & \text{if } x \geq 0 \\
1 & \text{if } x < 0
\end{cases}
\] |
|
LaTeX will then take care of defining and or aligning the columns.
Within cases, text style math is used with results such as:
Display style may be used instead, by using the dcases environment[2] from mathtools:
\[
a =
\begin{dcases}
\int x\, \mathrm{d} x\\
b^2
\end{dcases}
\] |
|
Often the second column consists mostly of normal text. To set it in the normal Roman font of the document, the dcases* environment may be used:[2]
\[
f(x) = \begin{dcases*}
x & when $x$ is even\\
-x & when $x$ is odd
\end{dcases*}
\] |
|
Other environments
[edit | edit source]Although align and align* are the most useful, there are several other environments that may also be of interest:
Environment name | Description | Notes |
---|---|---|
eqnarray and eqnarray* | Similar to align and align* | Not recommended because spacing is inconsistent |
multline and multline*[1] | First line left aligned, last line right aligned | Equation number aligned vertically with first line and not centered as with other environments |
gather and gather*[1] | Consecutive equations without alignment | |
flalign and flalign*[1] | Similar to align, but left aligns first equation column, and right aligns last column | |
alignat and alignat*[1] | Takes an argument specifying number of columns. Allows control of the horizontal space between equations | This environment takes one argument, the number of “equation columns”: count the maximum number of & s in any row, add 1 and divide by 2. [32]
|
There are also a few environments that don't form a math environment by themselves and can be used as building blocks for more elaborate structures:
Math environment name | Description |
---|---|
gathered[1] | Allows gathering equations to be set under each other. |
split[1] | Similar to align, but used inside another displayed mathematics environment and only supports a single equation column (i.e. a single & symbol).
|
aligned[1] | Similar to align, to be used inside another mathematics environment. |
alignedat[1] | Similar to alignat, and likewise takes an additional argument specifying the number of columns of equations to set. It can stack inside alignat. |
For example:
\begin{equation}
\left.\begin{aligned}
B'&=-\partial \times E,\\
E'&=\partial \times B - 4\pi j,
\end{aligned}
\right\}
\qquad \text{Maxwell's equations}
\end{equation} |
|
\begin{alignat}{2}
\sigma_1 &= x + y &\quad \sigma_2 &= \frac{x}{y} \\
\sigma_1' &= \frac{\partial x + y}{\partial x} & \sigma_2'
&= \frac{\partial \frac{x}{y}}{\partial x}
\end{alignat} |
|
\begin{gather*}
a_0=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}f(x)\,\mathrm{d}x\\[6pt]
\begin{split}
a_n=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}f(x)\cos nx\,\mathrm{d}x=\\
=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}x^2\cos nx\,\mathrm{d}x
\end{split}\\[6pt]
\begin{split}
b_n=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}f(x)\sin nx\,\mathrm{d}x=\\
=\frac{1}{\pi}\int\limits_{-\pi}^{\pi}x^2\sin nx\,\mathrm{d}x
\end{split}\\[6pt]
\end{gather*} |
Indented Equations
[edit | edit source]To indent an equation, you can set fleqn in the document class and then specify a certain value for the \mathindent
variable:
\documentclass[a4paper,fleqn]{report}
\usepackage{amsmath}
\setlength{\mathindent}{1cm}
\begin{document}
\noindent Euler's formula is given below:
\begin{equation*}
e^{ix} = \cos{x} + i \sin{x}.
\end{equation*}
\noindent This is a very important formula.
\end{document} |
Page breaks in math environments
[edit | edit source]To suggest that LaTeX insert a page break inside an amsmath environment, you may use the \displaybreak
command before the line break. Just as with \pagebreak
, \displaybreak
can take an optional argument between 0 and 4 denoting the level of desirability of a page break. Whereas 0 means "it is permissible to break here", 4 forces a break. No argument means the same as 4.
Alternatively, you may enable automatic page breaks in math environments with \allowdisplaybreaks
. It too can have an optional argument denoting the priority of page breaks in equations. Similarly, 1 means "allow page breaks but avoid them" and 4 means "break whenever you want". You can prohibit a page break after a given line using \\*
.
LaTeX will insert a page break into a long equation if it has additional text added using \intertext{}
without any additional commands.
Specific usage may look like this:
\begin{align*}
&\vdots\\
&=12+7 \int_0^2
\left(
-\frac{1}{4}\left(e^{-4t_1}+e^{4t_1-8}\right)
\right)\,dt_1\displaybreak[3]\\
&= 12-\frac{7}{4}\int_0^2 \left( e^{-4t_1}+e^{4t_1-8} \right)\,dt_1\\
&\vdots %
\end{align*} |
Page breaks before display maths (of all various forms) are controlled by \predisplaypenalty
. Its default 10000 means never break immediately before a display. Knuth (TeXbook chapter 19) explains this as a printers' tradition not to have a displayed equation at the start of a page. It can be relaxed with
\predisplaypenalty=0 |
Sometimes an equation might look best kept together preceding text by a higher penalty, for example, a single-line paragraph about a single-line equation, especially at the end of a section.
Boxed Equations
[edit | edit source]For a single equation or alignment building block, with the tag outside the box, use \boxed{}
:
\begin{equation}
\boxed{x^2+y^2 = z^2}
\end{equation} |
If you want the entire line or several equations to be boxed, use a minipage inside an \fbox{}
:
\fbox{
\addtolength{\linewidth}{-2\fboxsep}%
\addtolength{\linewidth}{-2\fboxrule}%
\begin{minipage}{\linewidth}
\begin{equation}
x^2+y^2=z^2
\end{equation}
\end{minipage}
} |
There is also the mathtools \Aboxed{}
which is able to box across alignment marks:
\begin{align*}
\Aboxed{ f(x) & = \int h(x)\, dx} \\
& = g(x)
\end{align*} |
Custom operators
[edit | edit source]Although many common operators are available in LaTeX, sometimes you will need to write your own, e.g. to typeset the argmax operator. The \operatorname
and \operatorname*
commands[1] display custom operators; the *
version sets the underscored option underneath like the \lim
operator:
\[
\operatorname{arg\,max}_a f(a)
= \operatorname*{arg\,max}_b f(b)
\] |
|
However, if the operator is frequently used, it is preferable to define a new operator that can be used throughout the entire document. The \DeclareMathOperator
and \DeclareMathOperator*
commands[1] are specified in the header of the document:
\DeclareMathOperator*{\argmax}{arg\,max} |
This defines a new command which may be referred to in the body:
\[
\argmax_c f(c)
\] |
|
Advanced formatting
[edit | edit source]Limits
[edit | edit source]There are defaults for placement of subscripts and superscripts. For example, limits for the lim operator are usually placed below the symbol:
\begin{equation}
\lim_{a\to \infty} \tfrac{1}{a}
\end{equation} |
|
To override this behavior, use the \nolimits
operator:
\begin{equation}
\lim\nolimits_{a\to \infty} \tfrac{1}{a}
\end{equation} |
|
A lim in running text (inside $...$
) will have its limits placed on the side, so that additional leading won't be required. To override this behavior, use the \limits
command.
Similarly one can put subscripts under a symbol that usually has them on the side:
\begin{equation}
\int_a^b x^2 \mathrm{d} x
\end{equation} |
|
Limits below and under:
\begin{equation}
\int\limits_a^b x^2 \mathrm{d} x
\end{equation} |
|
To change the default placement of summation-type symbols to the side for every case, add the nosumlimits option to the amsmath package. To change the placement for integral symbols, add intlimits to the options. nonamelimits can be used to change the default for named operators like det, min, lim, etc.
To produce one-sided limits, use \underset
as follows:
\begin{equation}
\lim_{a \underset{>}{\to} 0} \frac{1}{a}
\end{equation} |
|
Subscripts and superscripts
[edit | edit source]You can place symbols in subscript or superscript (in summation style symbols) with \nolimits
:
\begin{equation}
\sum\nolimits' C_n
\end{equation} |
|
It's impossible to mix them with typical usage of such symbols:
\begin{equation}
\sum_{n=1}\nolimits' C_n
\end{equation} |
|
To add both a prime and a limit to a symbol, one might use the \sideset
command:
\begin{equation}
\sideset{}{'}\sum_{n=1}C_n
\end{equation} |
|
It is very flexible: for example, to put letters in each corner of the symbol use this command:
\begin{equation}
\sideset{_a^b}{_c^d}\sum
\end{equation} |
|
If you wish to place them on the corners of an arbitrary symbol, you should use \fourIdx
from the fouridx package.
But a simple grouping can also solve the problem:
\begin{equation}
{\sum\limits_{n=1} }'C_n
\end{equation} |
|
since a math operator can be used with limits or no limits. If you want to change its state, simply group it. You can make it another math operator if you want, and then you can have limits and then limits again.
Multiline subscripts
[edit | edit source]To produce multiline subscript, use the \substack
command:
\begin{equation}
\prod_{\substack{
1\le i \le n\\
1\le j \le m}}
M_{i,j}
\end{equation} |
|
Text in aligned math display
[edit | edit source]To add small interjections in math environments, use the \intertext
command:
\begin{minipage}{3in}
\begin{align*}
\intertext{If}
A &= \sigma_1+\sigma_2\\
B &= \rho_1+\rho_2\\
\intertext{then}
C(x) &= e^{Ax^2+\pi}+B
\end{align*}
\end{minipage} |
Note that any usage of this command does not change the alignment.
Also, in the above example, the command \shortintertext{}
from the mathtools package could have been used instead of \intertext
to reduce the amount of vertical white space added between the lines.
Changing font size
[edit | edit source]There may be a time when you would prefer to have some control over the font size. For example, using text-mode maths, by default a simple fraction will look like this: , whereas you may prefer to have it displayed larger, like when in display mode, but still keeping it in-line, like this: .
A simple approach is to utilize the predefined sizes for maths elements:
Size command | Description |
---|---|
\displaystyle
|
Size for equations in display mode |
\textstyle
|
Size for equations in text mode |
\scriptstyle
|
Size for first sub/superscripts |
\scriptscriptstyle
|
Size for subsequent sub/superscripts |
A classic example to see this in use is typesetting continued fractions (though it's better to use the \cfrac
command[1] described in the Mathematics chapter instead of the method provided below). The following code provides an example.
\begin{equation}
x = a_0 + \frac{1}{a_1 + \frac{1}{a_2 + \frac{1}{a_3 + a_4}}}
\end{equation} |
|
As you can see, as the fractions continue, they get smaller (although they will not get any smaller than in this example, where they have reached the \scriptstyle
limit). If you want to keep the size consistent, you could declare each fraction to use the display style instead; e.g.
\begin{equation}
x = a_0 + \frac{1}{\displaystyle a_1
+ \frac{1}{\displaystyle a_2
+ \frac{1}{\displaystyle a_3 + a_4}}}
\end{equation} |
|
Another approach is to use the \DeclareMathSizes
command to select your preferred sizes. You can only define sizes for \displaystyle
, \textstyle
, etc. One potential downside is that this command sets the global maths sizes, as it can only be used in the document preamble.
But it's fairly easy to use: \DeclareMathSizes{ds}{ts}{ss}{sss}
, where ds is the display size, ts is the text size, etc. The values you input are assumed to be point (pt) size.
Note that the changes only take place if the value in the first argument matches the current document text size. It is therefore common to see a set of declarations in the preamble, in the event of the main font being changed. E.g.,
\DeclareMathSizes{10}{18}{12}{8} % For size 10 text
\DeclareMathSizes{11}{19}{13}{9} % For size 11 text
\DeclareMathSizes{12}{20}{14}{10} % For size 12 text |
Forcing \displaystyle for all math in a document
[edit | edit source]Put
\everymath{\displaystyle} |
before
\begin{document} |
to force all math to
\displaystyle |
.
Adjusting vertical white space around displayed math
[edit | edit source]There are four parameters that control the vertical white space around displayed math:
\abovedisplayskip=12pt
\belowdisplayskip=12pt
\abovedisplayshortskip=0pt
\belowdisplayshortskip=7pt |
Short skips are used if the preceding line ends, horizontally, before the formula. These parameters must be set after
\begin{document} |
.
Notes
[edit | edit source]
Theorems
[edit | edit source]With "theorem" we can mean any kind of labelled enunciation that we want to look separated from the rest of the text and with sequential numbers next to it. This approach is commonly used for theorems in mathematics, but can be used for anything. LaTeX provides a command that will let you easily define any theorem-like enunciation.
Basic theorems
[edit | edit source]First of all, make sure you have the amsthm package enabled:
\usepackage{amsthm}
The easiest is the following:
\newtheorem{name}{Printed output}
put it in the preamble. The first argument is the name you will use to reference it, the second argument is the output LaTeX will print whenever you use it. For example:
\newtheorem{mydef}{Definition}
will define the mydef
environment; if you use it like this:
\begin{mydef}
Here is a new definition
\end{mydef}
It will look like this:
with line breaks separating it from the rest of the text.
Theorem counters
[edit | edit source]Often the counters are determined by section, for example "Theorem 2.3" refers to the 3rd theorem in the 2nd section of a document. In this case, specify the theorem in the preamble as follows:
\newtheorem{theorem}{Theorem}[section]
and use it when needed:
\begin{theorem}
If $A$ is positive definite symmetric,
\end{theorem}
or, with a generic 'name' to output 'Printed output', add 'numberby':
\newtheorem{name}{Printed output}[numberby]
where numberby is the name of the section level (section/subsection/etc.) at which the numbering is to take place.
By default, each theorem uses its own counter. However it is common for similar types of theorems (e.g. Theorems, Lemmas and Corollaries) to share a counter. In this case, define subsequent theorems as:
\newtheorem{name}[counter]{Printed output}
where counter is the name of the counter to be used. Usually this will be the name of the master theorem.
The \newtheorem command may have at most one optional argument.
You can also create a theorem environment that is not numbered by using the newtheorem*
command[1]. For instance,
\newtheorem*{mydef}{Definition}
defines the mydef
environment, which will generate definitions without numbering. This requires amsthm
package.
Proofs
[edit | edit source]The proof
environment[1] can be used for adding the proof of a theorem. The basic usage is:
\begin{proof}
Here is my proof
\end{proof}
It just adds Proof in italics at the beginning of the text given as argument and a white square (Q.E.D. symbol, also known as a tombstone) at the end of it. If you are writing in another language than English, just use babel with the right argument and the word Proof printed in the output will be translated accordingly; anyway, in the source the name of the environment remains proof
.
If you would like to manually name the proof, include the name in square brackets:
\begin{proof}[Proof of important theorem]
Here is my important proof
\end{proof}
If the last line of the proof is displayed math then the Q.E.D. symbol will appear on a subsequent empty line. To put the Q.E.D. symbol at the end of the last line, use the \qedhere
command:
\begin{proof}
Here is my proof:
\[
a^2 + b^2 = c^2 \qedhere
\]
\end{proof}
The method above does not work with the deprecated environment eqnarray*
. Use align*
instead.
To use a custom Q.E.D. symbol, redefine the \qedsymbol command. To hide the Q.E.D. symbol altogether, redefine it to be blank:
\renewcommand{\qedsymbol}{}
Theorem styles
[edit | edit source]It adds the possibility to change the output of the environments defined by \newtheorem
using the \theoremstyle
command[1] in the header:
\theoremstyle{stylename}
the argument is the style you want to use. All subsequently defined theorems will use this style. Here is a list of the possible pre-defined styles:
stylename | Description | Appearance |
---|---|---|
plain | Used for theorems, lemmas, propositions, etc. (default) | Theorem 1. Theorem text. |
definition | Used for definitions and examples | Definition 2. Definition text. |
remark | Used for remarks and notes | Remark 3. Remark text. |
Custom styles
[edit | edit source]To define your own style, use the \newtheoremstyle
command[1]:
\newtheoremstyle{stylename}% name of the style to be used
{spaceabove}% measure of space to leave above the theorem. E.g.: 3pt
{spacebelow}% measure of space to leave below the theorem. E.g.: 3pt
{bodyfont}% name of font to use in the body of the theorem
{indent}% measure of space to indent
{headfont}% name of head font
{headpunctuation}% punctuation between head and body
{headspace}% space after theorem head; " " = normal interword space
{headspec}% Manually specify head
(Any arguments that are left blank will assume their default value). Here is an example headspec:
\thmname{#1}\thmnumber{ #2}:\thmnote{ #3}
which would look something like:
Definition 2: Topology
for the following:
\begin{definition}[Topology]...
(The note argument, which in this case is Topology, is always optional, but will not appear by default unless you specify it as above in the head spec).
Conflicts
[edit | edit source]The theorem environment conflicts with other environments, for example wrapfigure. A work around is to redefine theorem, for example the following way:
% Fix latex
\def\smallskip{\vskip\smallskipamount}
\def\medskip{\vskip\medskipamount}
\def\bigskip{\vskip\bigskipamount}
% Hand made theorem
\newcounter{thm}[section]
\renewcommand{\thethm}{\thesection.\arabic{thm}}
\def\claim#1{\par\medskip\noindent\refstepcounter{thm}\hbox{\bf \arabic{chapter}.\arabic{section}.\arabic{thm}. #1.}
\it\ %\ignorespaces
}
\def\endclaim{
\par\medskip}
\newenvironment{thm}{\claim}{\endclaim}
In this case theorem looks like:
\begin{thm}{Claim}\label{lyt-prob}
Let it be.
Then you know.
\end{thm}
Notes
[edit | edit source]External links
[edit | edit source]Chemical Graphics
[edit | edit source] This page was last edited 137 months ago, and may be abandoned This page has not been edited since 12 March 2013, but other pages in this book might have been. Check out related changes to see what the state of this book is. You can help by editing and updating this book. Remove {{under construction}} from this page if it is not being actively edited. Ask for help at WB:PROJECTS. |
chemfig is a package used to draw 2D chemical structures. It is an alternative to ochem. Whereas ochem requires Perl to draw chemical structures, chemfig uses the tikz package to produce its graphics. chemfig is used by adding the following to the preamble:
\usepackage{chemfig}
Basic Usage
[edit | edit source]The primary command used in this package is \chemfig{}:
\chemfig{<atom1><bond type>[<angle>,<coeff>,<tikz code>]<atom2>}
<angle> is the bond angle between two atoms (or nodes). There are three types of angles: absolute, relative, and predefined. Absolute angles give a precise angle (generally, 0 to 360, though they can also be negative), and are represented with the syntax [:<absolute angle>]. Relative angles require the syntax [::<relative angle>] and produce an angle relative to the angle of the preceding bond. Finally, predefined angles are whole numbers from 0 to 7 indicating intervals of 45 degrees. These are produced with the syntax [< predefined angle>]. The predefined angles and their corresponding absolute angles are represented in the diagram below.
\chemfig{(-[:0,1.5,,,draw=none]\scriptstyle\color{red}0)
(-[1]1)(-[:45,1.5,,,draw=none]\scriptstyle\color{red}45)
(-[2]2)(-[:90,1.5,,,draw=none]\scriptstyle\color{red}90)
(-[3]3)(-[:135,1.5,,,draw=none]\scriptstyle\color{red}135)
(-[4]4)(-[:180,1.5,,,draw=none]\scriptstyle\color{red}180)
(-[5]5)(-[:225,1.5,,,draw=none]\scriptstyle\color{red}225)
(-[6]6)(-[:270,1.5,,,draw=none]\scriptstyle\color{red}270)
(-[7]7)(-[:315,1.5,,,draw=none]\scriptstyle\color{red}315)
-0} |
<bond type> describes the bond attaching <atom1> and <atom2>. There are 9 different bond types:
\chemfig{A-B}\\
\chemfig{A=B}\\
\chemfig{A~B}\\
\chemfig{A>B}\\
\chemfig{A<B}\\
\chemfig{A>:B}\\
\chemfig{A<:B}\\
\chemfig{A>|B}\\
\chemfig{A<|B}\\ |
\chemfig{C(-[:0]H)(-[:90]H)(-[:180]H)(-[:270]H)}
<coeff> represents the factor by which the bond's length will be multiplied.
<tikz code> includes additional options regarding the color or style of the bond.
A methane molecule, for instance, can be produced with the following code:
\chemfig{C(-[:0]H)(-[:90]H)(-[:180]H)(-[:270]H)} |
Linear molecules (such as methane) are a weak example of this, but molecules are formed in chemfig by nesting.
Skeletal Diagrams
[edit | edit source]Skeleton diagrams can be produced as follows:
\chemfig{-[:30]-[:-30]-[:30]} |
\chemfig{-[:30]=[:-30]-[:30]} |
Rings
[edit | edit source]Rings follow the syntax <atom>*<n>(code), where "n" indicates the number of sides in the ring and "code" represents the specific content of each ring (bonds and atoms).
\chemfig{A*6(-B-C-D-E-F-)} |
\chemfig{A*5(-B-C-D-E-)} |
\chemfig{*6(=-=-=-)} |
\chemfig{**5(------)} |
Lewis Structures
[edit | edit source]Lewis structures use the syntax \charge{<position1>=<charge1>,<position2>=<charge2>...}{atom}
, where <position>
is in polar coordinates as <angle>:<shift>
, though the :<shift>
can be omitted if no additional shift is required. In the charge field, \.
and \:
will give unpaired and paired electrons respectively. Paired electrons can also be represented by a bar, using \|
.
\charge{0=\.,90=\.,180=\.,270=\.}{C} |
Lewis structures can also be included within \chemfig{}
.
\chemfig{H-[:52.24]\charge{45=\:,135=\:}{O}-[::-104.48]H} |
Ions
[edit | edit source]For example, consider an acetate ion:
\chemfig{-(-[1]O^{-})=[7]O} |
Because the chemfig commands enters the math mode, ion charges can be added as superscripts (one caveat: a negative ion requires that the minus sign be enclosed in brackets, as in the example).
The charge of an ion can be circled by using \oplus and \ominus:
\chemfig{-(-[1]O^{\ominus})=[7]O} |
Alternatively, charges can be placed above ions using \chemabove{}{}:
\chemfig{-\chemabove{N}{\scriptstyle\oplus}(=[1]O)-[7]O^{\ominus}} |
Resonance Structures and Formal Charges
[edit | edit source]Resonance structures require a few math commands:
% see "Advanced Mathematics" for use of \left and \right
% add to preamble:
% \usepackage{mathtools} % \Longleftrightarrow
$\left\{\chemfig{O-N(=[:60]O)-[:300]O}\right\}
\Longleftrightarrow
\left\{\chemfig{O=N(-[:60]O)-[:300]O}\right\}
\Longleftrightarrow
\left\{\chemfig{O-N(-[:60]O)=[:300]O}\right\}$
Chemical Reactions
[edit | edit source]Commands \chemrel and \chemsign were removed from chemfig package in latest versions, so in order to draw chemical reactions, one must instead use respectively \arrow and \+ commands in a block surrounded with \schemestart and \schemestop.
There are a few types of arrows that can be drawn with the \arrow command:
\schemestart A\arrow{->}B\schemestop\par % by default
\schemestart A\arrow{-/>}B \schemestop\par
\schemestart A\arrow{<-}B \schemestop\par
\schemestart A\arrow{<->}B \schemestop\par
\schemestart A\arrow{<=>}B \schemestop\par
\schemestart A\arrow{<->>}B \schemestop\par
\schemestart A\arrow{<<->}B \schemestop\par
\schemestart A\arrow{0}B \schemestop\par
\schemestart A\arrow{-U>}B \schemestop\par
\schemestart
A\arrow[,,->] B\arrow[,,-{Triangle[slant=0.5,blue,width=10pt]}]
C\arrow[,,-{CF[sharp]}] D \+ E
\schemestop
For more details on the \arrow command and chemical reactions in chemfig in general, consult the Part IV "Reaction schemes" of the chemfig documentation file.
Older versions
[edit | edit source]Chemical reactions can be created with the following commands:
\chemrel[<arg1>][<arg2>]{<arrow code>}
\chemsign+ % produces a +
In \chemrel{}, <arg1> and <arg2> represent text placed above and below the arrow, respectively.
There are four types of arrows that can be produced with \chemrel{}:
A\chemrel{->}B\par
A\chemrel{<-}B\par
A\chemrel{<->}B\par
A\chemrel{<>}B
Naming Chemical Graphics
[edit | edit source]Molecules can be named with the command
\chemname[<dim>]{\chemfig{<code of the molecule>}}{<name>}
<dim> is inserted between the bottom of the molecule and the top of the name defined by <name>. It is 1.5ex by default.
<name> will be centered relative to the molecule it describes.
\schemestart
\chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid}
\+
\chemname{\chemfig{R’OH}}{Alcohol}
\arrow{->}
\chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester}
\+
\chemname{\chemfig{H_2O}}{Water}
\schemestop
In the reaction above, \chemname{} inserts 1.5ex plus the depth of the carboxylic acid molecule in between each molecule and their respective names. This is because the graphic for the first molecule in the reaction (carboxylic acid) extends deeper than the rest of the molecules. A different result is produced by putting the alcohol first:
\schemestart
\chemname{\chemfig{R’OH}}{Alcohol}
\+
\chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid}
\arrow{->}
\chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester}
\+
\chemname{\chemfig{H_2O}}{Water}
\schemestop
This is fixed by adding \chemnameinit{<deepest molecule>} before the first instance of \chemname{} in a reaction and by adding \chemnameinit{} after the reaction:
\schemestart
\chemnameinit{\chemfig{R-C(-[:-30]OH)=[:30]O}}
\chemname{\chemfig{R’OH}}{Alcohol}
\+
\chemname{\chemfig{R-C(-[:-30]OH)=[:30]O}}{Carboxylic acid}
\arrow{->}
\chemname{\chemfig{R-C(-[:-30]OR’)=[:30]O}}{Ester}
\+
\chemname{\chemfig{H_2O}}{Water}
\chemnameinit{}
\schemestop
Lastly, adding \\ in <name> will produce a line-break, allowing the name to span multiple lines.
Advanced Graphics
[edit | edit source]For advanced commands and examples, refer to the chemfig manual, where a more thorough and complete introduction to the package can be found.
Chemical Formulae
[edit | edit source]If you need to typeset chemical formulae, you have the choice between two very good packages: mhchem
and chemmacros
.
Package mhchem
[edit | edit source]mhchem is a package used to typeset chemical formulae and equations. As well as typeset basic 2D chemical structures. To use this package, add the following to your preamble:
\usepackage[version=4]{mhchem}
Chemical species are included using the \ce command. For example
\ce{3H2O} \\
\ce{1/2H2O} \\
\ce{AgCl2-} \\
\ce{H2_{(aq)}} \\
renders:
For more examples, see meta:Help:Displaying a formula#Chemistry 2.
A few things here are automatically typeset; The 2 in \ce{H2O} is automatically subscripted without requiring additional commands. The amount of the species precedes the formula. 1/2 and other fractional amounts are automatically typeset as in \ce{1/2H2O}. The charge in \ce{AgCl2-} is automatically superscripted. If the charge is neither +1 nor -1, a ^ will superscript it, as in \ce{AgCl2-}. The phase is not automatically subscripted and needs to be enclosed in parenthesis preceded with a _ as in \ce{H2_{(aq)}.
Since February 2016, the mhchem package is also available in TeX in MediaWiki sites like Wikipedia, using the tag <ce>...</ce>
.
Package chemformula
[edit | edit source]chemformula is a package from a much bigger chemistry bundle, used to typeset chemical formulae, equations, and basic 2D chemical structures. The package uses a slightly different syntax compared to mhchem
. Package chemmacros
will be of great interest to people doing chemistry related work.
To use this package, add the following to your preamble:
\usepackage{chemformula}
Chemical species are included using the \ch command. For example
\ch{3 H2O} \\
\ch{1/2 H2O} \\
\ch{AgCl2-} \\
\ch{H2_{(aq)}} \\
renders:
As you can see, the syntax is almost the same.
XyMTeX package
[edit | edit source]The following code produces the image for corticosterone below.
\documentclass{letter}
\usepackage{epic,carom}
\pagestyle{empty}
\begin{document}
\begin{picture}(1000,500)
\put(0,0){\steroid[d]{3D==O;{{10}}==\lmoiety{H$_{3}$C};{{13}}==\lmoiety{H$_{3}$C};{{11}}==HO}}
\put(684,606){\sixunitv{}{2D==O;1==OH}{cdef}}
\end{picture}
\end{document}
Algorithms
[edit | edit source]LaTeX has several packages for typesetting algorithms in form of "pseudocode". They provide stylistic enhancements over a uniform style (i.e., all in typewriter font) so that constructs such as loops or conditionals are visually separated from other text. The pseudocode is usually put in an algorithm environment. For typesetting real code, written in a real programming language, consider the listings package described in Source Code Listings.
Typesetting
[edit | edit source]There are four notable packages algorithmic, algorithm2e, algorithmicx, and program,
Typesetting using the algorithmic package
[edit | edit source]The algorithmic package uses a different set of commands than the algorithmicx package. This is not compatible with revtex4-1. Basic commands are:
\STATE <text>
\IF{<condition>} \STATE {<text>} \ELSE \STATE{<text>} \ENDIF
\IF{<condition>} \STATE {<text>} \ELSIF{<condition>} \STATE{<text>} \ENDIF
\FOR{<condition>} \STATE {<text>} \ENDFOR
\FOR{<condition> \TO <condition> } \STATE {<text>} \ENDFOR
\FORALL{<condition>} \STATE{<text>} \ENDFOR
\WHILE{<condition>} \STATE{<text>} \ENDWHILE
\REPEAT \STATE{<text>} \UNTIL{<condition>}
\LOOP \STATE{<text>} \ENDLOOP
\REQUIRE <text>
\ENSURE <text>
\RETURN <text>
\PRINT <text>
\COMMENT{<text>}
\AND, \OR, \XOR, \NOT, \TO, \TRUE, \FALSE
Complete documentation is listed at [33] [dead link]. Most commands are similar to the algorithmicx equivalents, but with different capitalization. The package algorithms bundle at the ctan repository, dated 2009-08-24, describes both the algorithmic environment (for typesetting algorithms) and the algorithm floating wrapper (see below) which is designed to wrap around the algorithmic environment.
The algorithmic package is suggested for IEEE journals as it is a part of their default style sheet.[1]
How to rename require/ensure to input/output:
\floatname{algorithm}{Procedure}
\renewcommand{\algorithmicrequire}{\textbf{Input:}}
\renewcommand{\algorithmicensure}{\textbf{Output:}}
Typesetting using the algorithm2e package
[edit | edit source]The algorithm2e package (first released 1995, latest updated July 2017 according to the v5.2 manual) allows typesetting algorithms with a lot of customization. Like algorithmic, this package is also not compatible with Revtex-4.1.[2]
Unlike algorithmic, algorithm2e provides a relatively huge number of customization options to the algorithm suiting to the needs of various users. The CTAN-manual provides a comprehensible list of examples and full set of controls.
Typically, the usage between \begin{algorithm} and \end{algorithm} would be
1. Declaring a set of keywords(to typeset as functions/operators), layout controls, caption, title, header text (which appears before the algorithm's main steps e.g.: Input,Output)
2. Writing the main steps of the algorithm, with each step ending with a \;
This may be taken in analogy with writing a latex-preamble before we start the actual document.
The package is loaded like
\usepackage[]{algorithm2e}
and a simple example, taken from the v4.01 manual, is
\begin{algorithm}[H]
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\While{not at end of this document}{
read current\;
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\caption{How to write algorithms}
\end{algorithm}
which produces
More details are in the manual hosted on the ctan website.
Typesetting using the algorithmicx package
[edit | edit source]The algorithmicx package provides a number of popular constructs for algorithm designs. Put \usepackage{algpseudocode} in the preamble to use the algorithmic environment to write algorithm pseudocode (\begin{algorithmic}...\end{algorithmic}). You might want to use the algorithm environment (\usepackage{algorithm}) to wrap your algorithmic code in an algorithm environment (\begin{algorithm}...\end{algorithm}) to produce a floating environment with numbered algorithms.
The command \begin{algorithmic} can be given the optional argument of a positive integer, which if given will cause line numbering to occur at multiples of that integer. E.g. \begin{algorithmic}[5] will enter the algorithmic environment and number every fifth line.
Below is an example of typesetting a basic algorithm using the algorithmicx package (remember to add the \usepackage{algpseudocode} statement to your document preamble):
\begin{algorithmic}
\If {$i\geq maxval$}
\State $i\gets 0$
\Else
\If {$i+k\leq maxval$}
\State $i\gets i+k$
\EndIf
\EndIf
\end{algorithmic}
The LaTeX source can be written to a format familiar to programmers so that it is easy to read. This will not, however, affect the final layout in the document.
Basic commands have the following syntax:
Statement (\State causes a new line, can also be used in front of other commands)
\State $x\gets <value>$
Three forms of if-statements:
\If{<condition>} <text> \EndIf
\If{<condition>} <text> \Else <text> \EndIf
\If{<condition>} <text> \ElsIf{<condition>} <text> \Else <text> \EndIf
The third form accepts as many \ElsIf{} clauses as required. Note that it is \ElsIf and not \ElseIf.
Loops:
\For{<condition>} <text> \EndFor
\ForAll{<condition>} <text> \EndFor
\While{<condition>} <text> \EndWhile
\Repeat <text> \Until{<condition>}
\Loop <text> \EndLoop
Pre- and postcondition:
\Require <text>
\Ensure <text>
Functions
\Function{<name>}{<params>} <body> \EndFunction
\Return <text>
\Call{<name>}{<params>}
This command will usually be used in conjunction with a \State command as follows:
\Function{Increment}{$a$}
\State $a \gets a+1$
\State \Return $a$
\EndFunction
Comments:
\Comment{<text>}
Note to users who switched from the old algorithmic package: comments may be placed everywhere in the source; there are no limitations as in the old algorithmic package.
The algorithmicx package allows you to define your own environments.
To define blocks beginning with a starting command and ending with an ending command, use
\algblock[<block>]{<start>}{<end>}
This defines two commands \<start> and \<end> which have no parameters. The text displayed by them is \textbf{<start>} and \textbf{<end>}.
With \algblockdefx you can give the text to be output by the starting and ending command and the number of parameters for these commands. In the text the n-th parameter is referenced by #n.
\algblockdefx[<block>]{<start>}{<end>}
[<startparamcount>][<default value>]{<start text>}
[<endparamcount>][<default value>]{<end text>}
Example:
\algblock[Name]{Start}{End}
\algblockdefx[NAME]{START}{END}%
[2][Unknown]{Start #1(#2)}%
{Ending}
\algblockdefx[NAME]{}{OTHEREND}%
[1]{Until (#1)}
\begin{algorithmic}
\Start
\Start
\START[One]{x}
\END
\START{0}
\OTHEREND{\texttt{True}}
\End
\Start
\End
\End
\end{algorithmic}
More advanced customization and other constructions are described in the algorithmicx manual: http://mirror.ctan.org/macros/latex/contrib/algorithmicx/algorithmicx.pdf
Typesetting using the program package
[edit | edit source]The program package provides macros for typesetting algorithms. Each line is set in math mode, so all the indentation and spacing is done automatically. The notation |variable_name| can be used within normal text, maths expressions or programs to indicate a variable name. Use \origbar to get a normal | symbol in a program. The commands \A, \B, \P, \Q, \R, \S, \T and \Z typeset the corresponding bold letter with the next object as a subscript (eg \S1 typesets {\bf S$_1$} etc). Primes work normally, eg \S‘‘.
Below is an example of typesetting a basic algorithm using the program package (remember to add the \usepackage{program} statement to your document preamble):
\begin{program}
\mbox{A fast exponentiation procedure:}
\BEGIN \\ %
\FOR i:=1 \TO 10 \STEP 1 \DO
|expt|(2,i); \\ |newline|() \OD %
\rcomment{This text will be set flush to the right margin}
\WHERE
\PROC |expt|(x,n) \BODY
z:=1;
\DO \IF n=0 \THEN \EXIT \FI;
\DO \IF |odd|(n) \THEN \EXIT \FI;
\COMMENT{This is a comment statement};
n:=n/2; x:=x*x \OD;
\{ n>0 \};
n:=n-1; z:=z*x \OD;
|print|(z) \ENDPROC
\END
\end{program}
The commands \( and \) are redefined to typeset an algorithm in a minipage, so an algorithm can appear as a single box in a formula. For example, to state that a particular action system is equivalent to a WHILE loop you can write:
\[
\( \ACTIONS A:
A \EQ \IF \B{} \THEN \S{}; \CALL A
\ELSE \CALL Z \FI \QE
\ENDACTIONS \)
\EQT
\( \WHILE \B{} \DO \S{} \OD \)
\]
Dijkstra conditionals and loops:
\begin{program}
\IF x = 1 \AR y:=y+1
\BAR x = 2 \AR y:=y^2
\utdots
\BAR x = n \AR y:=\displaystyle\sum_{i=1}^n y_i \FI
\DO 2 \origbar x \AND x>0 \AR x:= x/2
\BAR \NOT 2 \origbar x \AR x:= \modbar{x+3} \OD
\end{program}
Loops with multiple exits:
\begin{program}
\DO \DO \IF \B1 \THEN \EXIT \FI;
\S1;
\IF \B2 \THEN \EXIT(2) \FI \OD;
\IF \B1 \THEN \EXIT \FI \OD
\end{program}
A Reverse Engineering Example.
Here's the original program:
\begin{program}
\VAR \seq{m := 0, p := 0, |last| := `` ''};
\ACTIONS |prog|:
|prog| \ACTIONEQ %
\seq{|line| := `` '', m := 0, i := 1};
\CALL |inhere| \ENDACTION
l \ACTIONEQ %
i := i+1;
\IF (i=(n+1)) \THEN \CALL |alldone| \FI ;
m := 1;
\IF |item|[i] \neq |last|
\THEN |write|(|line|); |line| := `` ''; m := 0;
\CALL |inhere| \FI ;
\CALL |more| \ENDACTION
|inhere| \ACTIONEQ %
p := |number|[i]; |line| := |item|[i];
|line| := |line| \concat `` '' \concat p;
\CALL |more| \ENDACTION
|more| \ACTIONEQ %
\IF (m=1) \THEN p := |number|[i];
|line| := |line| \concat ``, '' \concat p \FI ;
|last| := |item|[i];
\CALL l \ENDACTION
|alldone| \ACTIONEQ |write|(|line|); \CALL Z \ENDACTION \ENDACTIONS \END
\end{program}
And here's the transformed and corrected version:
\begin{program}
\seq{|line| := `` '', i := 1};
\WHILE i \neq n+1 \DO
|line| := |item|[i] \concat `` '' \concat |number|[i];
i := i+1;
\WHILE i \neq n+1 \AND |item|[i] = |item|[i-1] \DO
|line| := |line| \concat ``, '' \concat |number|[i]);
i := i+1 \OD ;
|write|(|line|) \OD
\end{program}
The package also provides a macro for typesetting a set like this: \set{x \in N | x > 0}.
Lines can be numbered by setting \NumberProgramstrue and numbering turned off with \NumberProgramsfalse
The algorithm environment
[edit | edit source]It is often useful for the algorithm produced by algorithmic to be "floated" to the optimal point
in the document to avoid it being split across pages. The algorithm environment provides this and a few other useful features. Include it by adding the
\usepackage{algorithm}
to your document's preamble. It is entered into by
\begin{algorithm}
\caption{<your caption for this algorithm>}
\label{<your label for references later in your document>}
\begin{algorithmic}
<algorithmic environment>
\end{algorithmic}
\end{algorithm}
Algorithm numbering
[edit | edit source]The default numbering system for the algorithm package is to number algorithms sequentially. This is often not desirable, particularly in large documents where numbering according to chapter is more appropriate. The numbering of algorithms can be influenced by providing the name of the document component within which numbering should be recommenced. The legal values for this option are: part, chapter, section, subsection, subsubsection or nothing (default). For example:
\usepackage[chapter]{algorithm}
List of algorithms
[edit | edit source]When you use figures or tables, you can add a list of them close to the table of contents; the algorithm package provides a similar command. Just put
\listofalgorithms
anywhere in the document, and LaTeX will print a list of the "algorithm" environments in the document with the corresponding page and the caption.
An example from the manual
[edit | edit source]This is an example taken from the manual (official manual, p.14)
\begin{algorithm} % enter the algorithm environment
\caption{Calculate $y = x^n$} % give the algorithm a caption
\label{alg1} % and a label for \ref{} commands later in the document
\begin{algorithmic} % enter the algorithmic environment
\REQUIRE $n \geq 0 \vee x \neq 0$
\ENSURE $y = x^n$
\STATE $y \Leftarrow 1$
\IF{$n < 0$}
\STATE $X \Leftarrow 1 / x$
\STATE $N \Leftarrow -n$
\ELSE
\STATE $X \Leftarrow x$
\STATE $N \Leftarrow n$
\ENDIF
\WHILE{$N \neq 0$}
\IF{$N$ is even}
\STATE $X \Leftarrow X \times X$
\STATE $N \Leftarrow N / 2$
\ELSE[$N$ is odd]
\STATE $y \Leftarrow y \times X$
\STATE $N \Leftarrow N - 1$
\ENDIF
\ENDWHILE
\end{algorithmic}
\end{algorithm}
- The official manual is located at
- http://mirrors.ctan.org/macros/latex/contrib/algorithms/algorithms.pdf
References
[edit | edit source]- The official manual for the algorithms package, Rogério Brito (2009), http://mirrors.ctan.org/macros/latex/contrib/algorithms/algorithms.pdf
Source Code Listings
[edit | edit source]There are many packages providing code listings and highlighting, below are most popular:
- listings
- very useful and functionality rich,
- minted
- minted is an alternative to listings which has become popular. It uses the external Python library Pygments for code highlighting, which as of February 2021 boasts over 537 supported languages and text formats. As the package relies on external Python code, the setup require a few more steps than a usual LaTeX package, so please have a look at their GitHub repo and their manual.
Using the listings package
[edit | edit source]Using the package listings you can add non-formatted text as you would do with \begin{verbatim}
but its main aim is to include the source code of any programming language within your document. If you wish to include pseudocode or algorithms, you may find Algorithms and Pseudocode useful also.
To use the package, you need:
\usepackage{listings} |
The listings package supports highlighting of all the most common languages and it is highly customizable. If you just want to write code within your document the package provides the lstlisting environment:
\begin{lstlisting}
Put your code here.
\end{lstlisting} |
Another possibility, that is very useful if you created a program on several files and you are still editing it, is to import the code from the source itself. This way, if you modify the source, you just have to recompile the LaTeX code and your document will be updated. The command is:
\lstinputlisting{source_filename.py} |
in the example there is a Python source, but it doesn't matter: you can include any file but you have to write the full file name. It will be considered plain text and it will be highlighted according to your settings, that means it doesn't recognize the programming language by itself. You can specify the language while including the file with the following command:
\lstinputlisting[language=Python]{source_filename.py} |
You can also specify a scope for the file.
\lstinputlisting[language=Python, firstline=37, lastline=45]{source_filename.py} |
Or
\lstinputlisting[language=Python, linerange={37-45,48-50}]{source_filename.py} |
This comes in handy if you are sure that the file will not change (at least before the specified lines). You may also omit the firstline or lastline parameter: it means everything up to or starting from this point.
This is a basic example for some Pascal code:
\documentclass{article}
\usepackage{listings} % Include the listings-package
\begin{document}
\lstset{language=Pascal} % Set your language (you can change the language for each code-block optionally)
\begin{lstlisting}[frame=single] % Start your code-block
for i:=maxint to 0 do
begin
{ do nothing }
end;
Write('Case insensitive ');
Write('Pascal keywords.');
\end{lstlisting}
\end{document}
Supported languages
[edit | edit source]It supports the following programming languages:
ABAP2,4, ACSL, Ada4, Algol4, Ant, Assembler2,4, Awk4, bash, Basic2,4, C#5, C++4, C4, Caml4, Clean, Cobol4, Comal, csh, Delphi, Eiffel, Elan, erlang, Euphoria, Fortran4, GCL, Go (golang), Gnuplot, Haskell, HTML, IDL4, inform, Java4, JVMIS, ksh, Lisp4, Logo, Lua2, make4, Mathematica1,4, Matlab, Mercury, MetaPost, Miranda, Mizar, ML, Modelica3, Modula-2, MuPAD, NASTRAN, Oberon-2, Objective C5 , OCL4, Octave, Oz, Pascal4, Perl, PHP, PL/I, Plasm, POV, Prolog, Promela, Python, R, Reduce, Rexx, RSL, Ruby, S4, SAS, Scilab, sh, SHELXL, Simula4, SQL, tcl4, TeX4, VBScript, Verilog, VHDL4, VRML4, XML, XSLT.
For some of them, several dialects are supported. For more information, refer to the documentation that comes with the package, it should be within your distribution under the name listings-*.dvi.
- Notes
- It supports Mathematica code only if you are typing in plain text format. You can't include *.NB files
\lstinputlisting{...}
as you could with any other programming language, but Mathematica can export in a pretty-formatted LaTeX source. - Specification of the dialect is mandatory for these languages (e.g.
language={[x86masm]Assembler}
). - Modelica is supported via the dtsyntax package available here.
- For these languages, multiple dialects are supported. C, for example, has ANSI, Handel, Objective and Sharp. See p. 12 of the listings manual for an overview.
- Defined as a dialect of another language
Settings
[edit | edit source]You can modify several parameters that will affect how the code is shown. You can put the following code anywhere in the document (it doesn't matter whether before or after \begin{document}
), change it according to your needs. The meaning is explained next to any line.
\usepackage{listings}
\usepackage{color}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}
\lstset{
backgroundcolor=\color{white}, % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}; should come as last argument
basicstyle=\footnotesize, % the size of the fonts that are used for the code
breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
breaklines=true, % sets automatic line breaking
captionpos=b, % sets the caption-position to bottom
commentstyle=\color{mygreen}, % comment style
deletekeywords={...}, % if you want to delete keywords from the given language
escapeinside={\%*}{*)}, % if you want to add LaTeX within your code
extendedchars=true, % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
firstnumber=1000, % start line enumeration with line 1000
frame=single, % adds a frame around the code
keepspaces=true, % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue}, % keyword style
language=Octave, % the language of the code
morekeywords={*,...}, % if you want to add more keywords to the set
numbers=left, % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt, % how far the line-numbers are from the code
numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
rulecolor=\color{black}, % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
showspaces=false, % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false, % underline spaces within strings only
showtabs=false, % show tabs within strings adding particular underscores
stepnumber=2, % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{mymauve}, % string literal style
tabsize=2, % sets default tabsize to 2 spaces
title=\lstname % show the filename of files included with \lstinputlisting; also try caption instead of title
}
- escapeinside
The escapeinside line needs an explanation. The option escapeinside={A}{B}
will define delimiters for escaping into LaTeX code, i.e. all the code between the string "A" and "B" will be parsed as LaTeX over the current listings style. In the example above, the comments for Octave start with %
, and they are going to be printed in the document unless they start with %*
, in which case they are read as LaTeX (with all LaTeX commands fulfilled) until they're closed with another *)
.
If you add the above paragraph, the following can be used to alter the settings within the code:
\lstset{language=C,caption={Descriptive Caption Text},label=DescriptiveLabel} |
There are many more options, check the official documentation.
Style definition
[edit | edit source]The package lets you define styles, i.e. profiles specifying a set of settings.
Example
\lstdefinestyle{customc}{
belowcaptionskip=1\baselineskip,
breaklines=true,
frame=L,
xleftmargin=\parindent,
language=C,
showstringspaces=false,
basicstyle=\footnotesize\ttfamily,
keywordstyle=\bfseries\color{green!40!black},
commentstyle=\itshape\color{purple!40!black},
identifierstyle=\color{blue},
stringstyle=\color{orange},
}
\lstdefinestyle{customasm}{
belowcaptionskip=1\baselineskip,
frame=L,
xleftmargin=\parindent,
language=[x86masm]Assembler,
basicstyle=\footnotesize\ttfamily,
commentstyle=\itshape\color{purple!40!black},
}
\lstset{escapechar=@,style=customc}
In our example, we only set two options globally: the default style and the escape character. Usage:
\begin{lstlisting}
#include <stdio.h>
#define N 10
/* Block
* comment */
int main()
{
int i;
// Line comment.
puts("Hello world!");
for (i = 0; i < N; i++)
{
puts("LaTeX is also great for programmers!");
}
return 0;
}
\end{lstlisting}
\lstinputlisting[caption=Scheduler, style=customc]{hello.c}
The C part will print as
Automating file inclusion
[edit | edit source]If you have a bunch of source files you want to include, you may find yourself doing the same thing over and over again. This is where macros show their real power.
\newcommand{\includecode}[2][c]{\lstinputlisting[caption=#2, escapechar=, style=custom#1]{#2}<!---->}
% ...
\includecode{sched.c}
\includecode[asm]{sched.s}
% ...
\lstlistoflistings
In this example, we create one command to ease source code inclusion. We set the default style to be customc. All listings will have their name as caption: we do not have to write the file name twice thanks to the macro. Finally we list all listings with this command from the listings package.
See Macros for more details.
Encoding issue
[edit | edit source]By default, listings does not support multi-byte encoding for source code.
The extendedchar
option only works for 8-bits encodings such as latin1.
To handle UTF-8, you should tell listings how to interpret the special characters by defining them like so
\lstset{literate=
{á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
{Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
{à}{{\`a}}1 {è}{{\`e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
{À}{{\`A}}1 {È}{{\`E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
{ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
{Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
{â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
{Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
{ã}{{\~a}}1 {ẽ}{{\~e}}1 {ĩ}{{\~i}}1 {õ}{{\~o}}1 {ũ}{{\~u}}1
{Ã}{{\~A}}1 {Ẽ}{{\~E}}1 {Ĩ}{{\~I}}1 {Õ}{{\~O}}1 {Ũ}{{\~U}}1
{œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
{ű}{{\H{u}}}1 {Ű}{{\H{U}}}1 {ő}{{\H{o}}}1 {Ő}{{\H{O}}}1
{ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {Ø}{{\O}}1 {å}{{\r a}}1 {Å}{{\r A}}1
{€}{{\euro}}1 {£}{{\pounds}}1 {«}{{\guillemotleft}}1
{»}{{\guillemotright}}1 {ñ}{{\~n}}1 {Ñ}{{\~N}}1 {¿}{{?`}}1 {¡}{{!`}}1
}
The above table will cover most characters in latin languages.
For a more detailed explanation of the usage of the literate
option check section 5.4 in the Listings Documentation.
Another possibility is to replace \usepackage{listings}
(in the preamble) with \usepackage{listingsutf8}
, but this will only work for \lstinputlisting{...}
.
Customizing captions
[edit | edit source]You can have fancy captions (or titles) for your listings using the caption package. Here is an example for listings.
\usepackage{caption}
\usepackage{listings}
\DeclareCaptionFont{white}{ \color{white} }
\DeclareCaptionFormat{listing}{
\colorbox[cmyk]{0.43, 0.35, 0.35,0.01 }{
\parbox{\textwidth}{\hspace{15pt}#1#2#3}
}
}
\captionsetup[lstlisting]{ format=listing, labelfont=white, textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize} }
% ...
\lstinputlisting[caption=My caption]{sourcefile.lang}
References
[edit | edit source]A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses.
Details and documentation about the Listings package can be found at its CTAN website.
Linguistics
[edit | edit source]Indexing
[edit | edit source]Glossary
[edit | edit source]Bibliography Management
[edit | edit source]More Bibliographies
[edit | edit source]LaTeX/More Bibliographies Template:PDF-Version Gliederung
Letters
[edit | edit source]Presentations
[edit | edit source]Teacher's Corner
[edit | edit source]Curriculum Vitae
[edit | edit source]LaTeX/Curriculum Vitae Template:PDF-Version Gliederung
Introducing Procedural Graphics
[edit | edit source]LaTeX/Introducing Procedural Graphics
MetaPost
[edit | edit source]Picture
[edit | edit source]PGF/TikZ
[edit | edit source]PSTricks
[edit | edit source]Xy-pic
[edit | edit source]Creating 3D graphics
[edit | edit source]LaTeX/Creating 3D graphics Template:PDF-Version Gliederung
Macros
[edit | edit source]Plain TeX
[edit | edit source]Creating Packages
[edit | edit source]Themes
[edit | edit source]LaTeX/Themes Template:PDF-Version Gliederung
Modular Documents
[edit | edit source]Collaborative Writing of LaTeX Documents
[edit | edit source]LaTeX/Collaborative Writing of LaTeX Documents
Export To Other Formats
[edit | edit source]LaTeX/Export To Other Formats Template:PDF-Version Gliederung
FAQ
[edit | edit source]Tips and Tricks
[edit | edit source]LaTeX/Tips and Tricks Template:PDF-Version Gliederung