Latex
Latex
Latex
PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Tue, 16 Apr 2013 15:51:01 UTC
Contents
Articles
Getting Started
Introduction Installation Installing Extra Packages Basics 1 1 7 19 25 36 36 46 57 64 70 79 86 95 109 113 132 137 150 164 175 185 193 193 199 205 209 214 217 217 236
Common Elements
Document Structure Text Formatting Paragraph Formatting Colors Fonts List Structures Special Characters Internationalization Rotations Tables Title Creation Page Layout Importing Graphics Floats, Figures and Captions Hyperlinks Labels and Cross-referencing
Mechanics
Errors and Warnings Lengths Counters Boxes Rules and Struts
Technical Texts
Mathematics Advanced Mathematics
247 253 260 271 278 291 291 298 305 326 333 333 341 354 358 363 363 366 368 376 385 394 398 401 401 408 420 424 430 430 438 449 457
Special Pages
Indexing Glossary Bibliography Management More Bibliographies
Special Documents
Letters Presentations Teacher's Corner Curriculum Vitae
Creating Graphics
Introducing Procedural Graphics MetaPost Picture PGF/TikZ PSTricks Xy-pic Creating 3D graphics
Programming
Macros Plain TeX Creating Packages Themes
Miscellaneous
Modular Documents Collaborative Writing of LaTeX Documents Export To Other Formats
Appendix
Authors Links Package Reference Sample LaTeX documents Index Command Glossary
References
Article Sources and Contributors Image Sources, Licenses and Contributors 506 509
Article Licenses
License 513
Getting Started
Introduction
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Introduction
2 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
Introduction
What is TeX?
TeX is a low-level markup and programming language created by Donald Knuth to typeset documents attractively and consistently. Knuth started writing the TeX typesetting engine in 1977 to explore the potential of the digital printing equipment that was beginning to infiltrate the publishing industry at that time, especially in the hope that he could reverse the trend of deteriorating typographical quality that he saw affecting his own books and articles. With the release of 8-bit character support in 1989, TeX development has been essentially frozen with only bug fixes released periodically. TeX is a programming language in the sense that it supports the if-else construct: you can make calculations with it (that are performed while compiling the document), etc., but you would find it very hard to do anything else but typesetting with it. The fine control TeX offers over document structure and formatting makes it a powerfuland formidabletool. TeX is renowned for being extremely stable, for running on many different kinds of computers, and for being virtually bug free. The version numbers of TeX are converging toward , with a current version number of 3.1415926. The name TeX is intended by its developer to be /'tx/, with the final consonant of loch or Bach. (Donald E. Knuth, The TeXbook) The letters of the name are meant to represent the capital Greek letters tau, epsilon, and chi, as TeX is an abbreviation of ( techn), Greek for both "art" and "craft", which is also the root word of technical. English speakers often pronounce it /'tk/, like the first syllable of technical. Programming in TeX has a very high learning curve, and requires a significant investment of time to build custom macros for text formatting. Fortunately, document preparation systems based on TeX, consisting of collections of pre-built macros, do exist. These pre-built macros are time saving, and automate certain repetitive tasks and help reduce user introduced errors; however, this convenience comes at the cost of complete design flexibility. One of the most popular macro packages is called LaTeX.
What is LaTeX?
LaTeX (pronounced either "Lah-tech" or "Lay-tech") is a macro package based on TeX created by Leslie Lamport. Its purpose is to simplify TeX typesetting, especially for documents containing mathematical formulae. Within the typesetting system, its name is formatted as LaTeX. Many later authors have contributed extensions, called packages or styles, to LaTeX. Some of these are bundled with most TeX/LaTeX software distributions; more can be found in the Comprehensive TeX Archive Network (CTAN [3] ). Since LaTeX comprises a group of TeX commands, LaTeX document processing is essentially programming. You create a text file in LaTeX markup, which LaTeX reads to produce the final document. This approach has some disadvantages in comparison with a WYSIWYG (What You See Is What You Get) program such as Openoffice.org Writer or Microsoft Word. In LaTeX: You don't (usually) see the final version of the document when editing it. You generally need to know the necessary commands for LaTeX markup. It can sometimes be difficult to obtain a certain look for the document. On the other hand, there are certain advantages to the LaTeX approach: Document sources can be read with any text editor and understood, unlike the complex binary and XML formats used with WYSIWYG programs. You can concentrate purely on the structure and contents of the document, not get caught up with superficial layout issues. You don't need to manually adjust fonts, text sizes, line heights, or text flow for readability, as LaTeX takes care of them automatically.
Introduction In LaTeX the document structure is visible to the user, and can be easily copied to another document. In WYSIWYG applications it is often not obvious how a certain formatting was produced, and it might be impossible to copy it directly for use in another document. The layout, fonts, tables and so on are consistent throughout the document. Mathematical formulae can be easily typeset. Indexes, footnotes, citations and references are generated easily. Since the document source is plain text, tables, figures, equations, etc. can be generated programmatically with any language. You are forced to structure your documents correctly. The LaTeX-like approach can be called WYSIWYM, i.e. What You See Is What You Mean: you can't see what the final version will look like while typing. Instead you see the logical structure of the document. LaTeX takes care of the formatting for you. The LaTeX document is a plain text file containing the content of the document, with additional markup. When the source file is processed by the macro package, it can produce documents in several formats. LaTeX natively supports DVI and PDF, but by using other software you can easily create PostScript, PNG, JPEG, etc.
Philosophy of use
Flexibility and modularity
One of the most frustrating things beginners and even advanced users might encounter using LaTeX is the lack of flexibility regarding the document design and layout. If you want to design your document in a very specific way, you may have trouble accomplishing this. Keep in mind that LaTeX does the formatting for you, and mostly the right way. If it is not exactly what you desired, then the LaTeX way is at least not worse, if not better. One way to look at it is that LaTeX is a bundle of macros for TeX that aims to carry out everything regarding document formatting, so that the writer only needs to care about content. If you really want flexibility, use plain TeX instead. One solution to this dilemma is to make use of the modular possibilities of LaTeX. You can build your own macros, or use macros developed by others. You are likely not the first person to face some particular formatting problem, and someone who encountered a similar problem before may have published their solution as a package. CTAN [4] is a good place to find many resources regarding TeX and derivative packages. It is the first place where you should begin searching.
Introduction
ConTeXt A TeX-based document preparation system (as LaTeX is) with a very consistent and easy syntax and support for pdfTeX, XeTeX and LuaTeX engines. It does not have the same objective as LaTeX however. LaTeX A TeX-based document preparation system designed by Leslie Lamport. It is actually a set of macros for TeX. It aims at taking care of the formatting process.
MetaFont A high-quality font system designed by Donald Knuth along TeX. MetaPost A descriptive vector graphics language based on MetaFont. TeX The original language designed by Donald Knuth.
Descriptions A TeX engine with Lua scripting engine embedded aiming at making TeX internals more flexible. The engines (PDF compilers). The engines (DVI compilers). a TeX engine which uses Unicode and supports widely popular .ttf and .otf fonts. See Fonts.
Introduction
Descriptions A TeX Live based distribution targetting Mac OS X. A TeX distribution for Windows. A cross-platform TeX distribution.
What next?
Next chapter we will procede to the installation. Then we will compile our first LaTeX file. Throughout this book you should also utilise other means for learning about LaTeX. Good sources are: the #latex [5] IRC channel on Freenode, the TeX Stack Exchange [6] Q&A, the TeX [7] FAQ, and the TeXample.net [8] Community.
References
[1] [2] [3] [4] [5] [6] [7] [8] http:/ / en. wikibooks. org/ w/ index. php?title=Template:LaTeX/ Top& action=edit http:/ / en. wikibooks. org/ w/ index. php?title=Template:LaTeX/ Contents& action=edit http:/ / www. ctan. org http:/ / www. ctan. org/ http:/ / webchat. freenode. net?channels=latex http:/ / tex. stackexchange. com/ http:/ / www. tex. ac. uk/ cgi-bin/ texfaq2html http:/ / www. texample. net/
Installation
Installation
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Installation
8 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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 an user account with an online LaTeX editor and continue this tutorial in the next chapter. These websites offer collaboration capabilities while allowing you to experiment with LaTeX syntax without having to bother with installing and configuring a distribution and an editor. When you later feel that you would benefit from having a standalone LaTeX installation, you can return to this chapter and follow the instructions below.
Installation LaTeX is not a program by itself, it is a language. Using LaTeX requires a bunch of tools. Acquiring them manually would result in downloading and installing multiple programs in order to have a suitable computer system that can be used to create LaTeX output, such as PDFs. TeX Distributions help the user in this way, in that it is a single step installation process that provides (almost) everything. At a minimum, you'll need a TeX distribution, a good text editor and a DVI or PDF viewer. More specifically, the basic requirement is to have a TeX compiler (which is used to generate output files from source), fonts, and the LaTeX macro set. Optional, and recommended installations include an attractive editor to write LaTeX source documents (this is probably where you will spend most of your time), and a bibliographic management program to manage references if you use them a lot.
Distributions
TeX and LaTeX are available for most computer platforms, since they were programmed to be very portable. They are most commonly installed using a distribution, such as teTeX, MiKTeX, or MacTeX. TeX distributions are collections of packages and programs (compilers, fonts, and macro packages) that enable you to typeset without having to manually fetch files and configure things. LaTeX is just a set of macro packages built for TeX. The recommended distributions for each of the major operating systems are: TeX Live [1] is a major TeX distribution for *BSD, GNU/Linux, Mac OS X and Windows. MiKTeX [2] is a Windows-specific distribution. MacTeX [3] 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.
Mac OS X
Mac OS X users may use MacTeX [6], a TeX Live-based distribution supporting TeX, LaTeX, AMSTeX, ConTeXt, XeTeX and many other core packages. Download MacTeX.mpkg.zip on the MacTeX page [3], unzip it and follow the instructions. Further information for Mac OS X users can be found on the TeX on Mac OS X Wiki [7]. Since Mac OS X is also a Unix-based system, TeX Live is naturally available through MacPorts Further information for Mac OS X users can be found on the TeX on Mac OS X Wiki [7].
[8]
and Fink
[9]
Installation
10
Microsoft Windows
Microsoft Windows users can install MiKTeX [10] onto their computer. It has an easy installer that take care of setting up the environment and downloading core packages. This distribution has advanced features, such as automatic installation of packages, and simple interfaces to modify settings, such as default paper sizes. There is also a port of TeX Live available for Windows.
Minimal installation
We will give you general guidelines to install a minimal TeX distribution, i.e. only for plain TeX. 1. Download the installer at http://mirror.ctan.org/systems/texlive/tlnet/install-tl-unx.tar.gz and extract it to a temporary folder. 2. Open a terminal in the extracted folder and log as root. 3. Change the umask to 022 to make sure other users will have read-only access to the installed distribution. # umask 022 1. Launch install-tl. 2. Select the minimal scheme (plain only). 3. You may want to change the directory options. For example you may want to hide your personal macro folder which is located at TEXMFHOME. It is ~/texmf by default. Replace it by ~/.texmf to hide it. 4. Now the options: 1. use letter size instead of A4 by default: mostly for users from the USA. 2. execution of restricted list of programs: it is recommended to select it for security reasons. Otherwise it allows the TeX engines to call any external program. You may still configure the list afterwards. 3. create format files: targetting a minimal disk space, the best choice depends on whether there is only one user on the system, then deselecting it is better, otherwise select it. From the help menu: "If this option is set, format files are created for system-wide use by the installer. Otherwise they are 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
Installation re-created when new packages are installed." 4. install font/macro doc tree: useful if you are a developper, but very space consuming. Turn it off if you want to save space. 5. install font/macro source tree: same as above. 6. Symlinks are fine by default, change it if you know what you are doing. 5. Select portable installation if you install the distribution to an optical disc, or any kind of external media. Leave to default for a traditional installation on the system hard drive. At this point it should display 1 collections out of 85, disk space required: 40 MB or a similar space usage. You can now proceed to installation: start installation to hard disk.
11
First test
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
Formerly, TeX distributions used to be configured with the texconfig tool from the teTeX distribution. TeX Live still features this tool, but recommends using its own tool instead: tlmgr. Note that as of January 2013 not all texconfig features are implemented by tlmgr. Only use texconfig when you cannot do what you want with tlmgr. List current installation options: tlmgr option You can change the install options: tlmgr option src 1 tlmgr option doc 0 tlmgr option 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
Now we have a running plainTeX 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. It may happen to install dependencies manually. Thankfully this is rarely too cumbersome. Other interesting packages:
Installation
# tlmgr install amsmath babel carlisle ec geometry graphics hyperref lm marvosym oberdiek parskip pdftex-def url
12
The essentials for math typesetting. Internationalization support. Bundle package required for some babel features. Resquired for T1 encoding. For page layout. The essentials to import graphics. PDF bookmarks, PDF followable links, link style, TOC links, etc. 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 parskip Bundle package required for some geometry features. Let you configure paragraph breaks and indents properly.
pdftex-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
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
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 aforementionned 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.
Installation
13
Editors
TeX and LaTeX source documents (as well as related files) are all text files, and can be opened and modified in almost any text editor. You should use a text editor (e.g. Notepad), not a word processor (Word, OpenOffice). Dedicated LaTeX editors are more useful than generic plain text editors, because they usually have autocompletion of commands, spell and error checking and handy macros.
Cross-platform
BaKoMa TeX BaKoMa TeX [12] is an editor for Windows and Mac OS with WYSIWYG-like features. It takes care of compiling the LaTeX source and updating it constantly to view changes to document almost in real time. Emacs Emacs [13] 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 theirs needs. In turn beginners may prefer using it in combination with AUCTeX [14] and Reftex (extensions that may be installed into the Emacs program). Depending on your configuration, Emacs can provide a complete LaTeX editing environment with auto-completion, spell-checking, a complete set of keyboard shortcuts, table of contents view, document preview and many other features. gedit-latex-plugin Gedit with gedit-latex-plugin [15] is also worth trying out for users of GNOME. GEdit is a cross-platform application for Windows, Mac, and Linux Gummi Gummi is a LaTeX editor for Linux, which compiles the output of pdflatex in realtime and shows it on the right half of the screen[16].
Screenshot of Gummi.
Installation LyX LyX is a popular LaTeX editor for Windows, Linux and Mac OS. It contains formula and table editors and shows visual clues of the final document on the screen enabling users to write LaTeX documents without worrying about the actual syntax[17]. TeXmaker TeXmaker [18] is a cross-platform editor very similar to Kile in features and user interface. In addition it has its own PDF viewer. TeXstudio TeXstudio [19] is a cross-platform open source LaTeX editor forked from Texmaker. TeXworks TeXworks is a dedicated TeX editor that is included in MiKTeX and TeX Live. It was developed with the idea that a simple interface is better than a cluttered one, and thus to make it easier for people in their early days with LaTeX to get to what they want to do: write their documents. TeXworks originally came about precisely because a math professor wanted his students to have a better initial experience with LaTeX. You can install TeXworks with the package manager of your Linux distribution or choose it as an install option in the Windows or Mac installer. Vim 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 [20] and Vim-LaTeX [21].
Screenshot of TeXworks on Ubuntu 12.10. LyX1.6.3
14
Installation Kile [22] is a LaTeX editor for KDE [23] (cross platform), providing a powerful GUI for editing multiple documents and compiling them with many different TeX compilers. Kile is based on Kate editor, has a quick access toolbar for symbols, document structure viewer, a console and customizable build options. Kile can be run in all operating systems that can run KDE. LaTeXila LaTeXila [24] is another text editor for Linux (Gnome).
Screenshot of Kile.
15
Mac OS X-only
TeXShop TeXShop [25] is a TeXworks-like editor and previewer for Mac OS that 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.
Windows-only
LEd LEd [26] TeXnicCenter TeXnicCenter [27] is a popular free and open source LaTeX editor for Windows. It also has a similar user interface to TeXmaker and Kile. WinEdt WinEdt [28] 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 in-built 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 WinShell [29]
Installation
16
Bibliography management
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
JabRef [30] Mendeley [31]
Screenshot of JabRef.
Mac OS X-only
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[32].
Viewers
Finally, you will need a viewer for the files LaTeX outputs. Normally LaTeX saves the final document as a .dvi (Device independent file format), but you will rarely want it to. DVI files do not contain embedded fonts and many document viewers are unable to open them.
Screenshot of BibDesk
Usually you will use a LaTeX compiler like pdflatex to produce a PDF file directly, or a tool like dvi2pdf to convert the DVI file to PDF format. Then you can view the result with any PDF viewer. Practically all LaTeX distributions have a DVI viewer for viewing the default output of latex, and also tools such as dvi2pdf for converting the result automatically to PDF and PS formats. Here follows a list of various PDF viewers. Adobe Reader epdfview Evince Foxit
Okular Sumatra
Installation Zathura
17
Online solutions
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. Google Documents [33] or LaTeX Lab [34] allows real-time simultaneous collaborative editing of text files for anyone with a Google account (and its option to make the document available through a URL makes local download and compilation easily scriptable). LIMSUP [35] is an online LaTeX editor allowing real time collaboration of LaTeX documents (announcement [36] ) Monkey TeX [37] is free and allows team sharing. publications.li [38] is a real-time collaborative LaTeX editor. ScribTeX.com [39] is one of the most mature systems available, with git push and pull access it allows for powerful version control. The new sign ups are now directed to use ShareLatex.com [40] however accounts are still available upon request. ShareLaTeX.com [40] is a secure cloud based LaTeX editor offering unlimited free project, well established it is the first real time collaborative editor. Premium accounts are available for extra features such as version control and Dropbox integration. SpanDeX [41] is a cloud-based LaTeX collaboration platform designed to make collaborating with LaTeX seamless and to reduce the learning curve to LaTeX. It offers simultaneous real-time editing and collaboration, live document preview, Dropbox integration, and a built-in LaTeX resource system. Verbosus [42] 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. writeLaTeX.com [43] is a secure, easy to use online LaTeX editor with integrated rapid preview - like EtherPad [44] for LaTeX. Start writing with one click (no signup required) and share the link. It supports real time preview, figures, bibliographies and custom styles.
Installation
18
References
[1] http:/ / www. tug. org/ texlive/ [2] http:/ / www. miktex. org/ [3] http:/ / www. tug. org/ mactex/ [4] teTeX Home Page (http:/ / www. tug. org/ tetex/ ) (Retrieved January 31, 2007) [5] http:/ / www. tug. org/ texlive/ acquire. html [6] http:/ / tug. org/ mactex/ [7] http:/ / mactex-wiki. tug. org/ [8] http:/ / www. macports. org/ [9] http:/ / www. finkproject. org/ [10] http:/ / miktex. org/ [11] http:/ / www. tug. org/ texlive/ acquire-netinstall. html [12] http:/ / bakoma-tex. com/ menu/ about. php [13] http:/ / www. gnu. org/ software/ emacs [14] http:/ / www. gnu. org/ software/ auctex/ [15] https:/ / live. gnome. org/ Gedit/ LaTeXPlugin [16] Gummi (http:/ / gummi. midnightcoding. org/ ) [17] LyX (http:/ / www. lyx. org/ ) [18] http:/ / www. xm1math. net/ texmaker/ [19] http:/ / texstudio. sourceforge. net/ [20] http:/ / www. vim. org/ scripts/ script. php?script_id=3109 [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] [33] [34] [35] [36] [37] [38] [39] [40] [41] [42] [43] [44] http:/ / vim-latex. sourceforge. net/ http:/ / kile. sourceforge. net/ http:/ / en. wikipedia. org/ wiki/ KDE_Software_Compilation_4 http:/ / latexila. sourceforge. net/ http:/ / www. uoregon. edu/ ~koch/ texshop/ http:/ / www. latexeditor. org/ http:/ / www. texniccenter. org/ http:/ / www. winedt. com/ http:/ / www. winshell. de/ http:/ / jabref. sourceforge. net/ http:/ / www. mendeley. com/ / BibDesk (http:/ / bibdesk. sourceforge. net/ ) http:/ / docs. google. com http:/ / docs. latexlab. org http:/ / www. limsup. com http:/ / www. digmi. org/ 2012/ 05/ 19/ limsup-real-time-latex-collaboration/ http:/ / monkeytex. bradcater. webfactional. com http:/ / www. publications. li http:/ / www. scribtex. com/ https:/ / www. sharelatex. com http:/ / spandex. io http:/ / www. verbosus. com https:/ / www. writelatex. com http:/ / en. wikipedia. org/ wiki/ Etherpad
19
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
20 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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 [1] which includes a link to Graham Williams' comprehensive package catalogue.
Installing Extra Packages 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 is 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 manage 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 [4]. 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.
21
Automatic installation
If on a system with a package manager or a portage tree, you can often find packages in the repositories. 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 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 manually installed, use tlmgr to manage packages individually. tlmgr install <package1> <package2> ... tlmgr remove <package1> <package2> ... The use of tlmgr is covered int the Installation chapter. If you cannot find the wanted package with any of the previous methods, see the manual installation.
Manual installation
Downloading packages
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 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.
22
Installing a package
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/. 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.
23
others tex/latex/packagename
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 Widows XP or later versions of Windows: Start -> All Programs -> MikTex -> Settings. In Settings menu choose the first tab and click on Refresh FNDB-button (MikTex will then check the Program Files directory and update the list of File Name DataBase). After that just verify by clicking 'OK'.
5. Update font maps If your package installed any TrueType or Type 1 fonts, you need to update the font mapping files in addition to updating the index. Your package author should have included a .map file for the fonts. The map updating program is usually some variant on updmap, depending on your distribution: TeX Live and MacTeX: updmap --enable 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.
Installing Extra Packages 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 she 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.
24
Package documentation
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 MiKTeX TeX Live Path %MIKTEX_DIR%\doc\latex $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>
25
External resources
The best way to look for LaTeX packages is the already mentioned CTAN: Search The TeX Catalogue Online [3]: Alphabetic catalogue [4] With brief descriptions [5] Topical catalogue [6] with packages sorted systematically Hierarchical [7] mirroring the CTAN folder hierarchy
[2]
See Also
LaTeX/Package Reference
References
[1] [2] [3] [4] [5] http:/ / www. ctan. org/ search. html http:/ / tug. ctan. org/ search. html http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ catalogue. html http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ alpha. html http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ brief. html
[6] http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ bytopic. html [7] http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ hier. html
Basics
LaTeX
Basics
26 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Basics
27 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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.
Basics 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.
28
Spaces
"Whitespace" characters, such as blank or tab, are treated uniformly as "space" by LaTeX. Several consecutive whitespace characters are treated as one "space". Whitespace at the start of a line is generally ignored, and a single line break is treated as whitespace. An empty line between two lines of text defines the end of a paragraph. Several empty lines are treated the same as one empty line. The text below is an example. On the left hand side is the text from the input file, and on the right hand side is the formatted output. It does not matter whether you enter one or several spaces after a word. An empty line starts a new paragraph.
It does not matter whether you enter one or several spaces after a word. An empty line starts a new paragraph.
Reserved Characters
The following symbols are reserved characters that either have a special meaning under LaTeX or are unavailable in all the fonts. If you enter them directly in your text, they will normally not print, but rather make LaTeX do things you did not intend. # $ % ^ & _ { } ~ \ As you will see, these characters can be used in your documents all the same by adding a prefix backslash: \# \$ \% \^{} \& \_ \{ \} \~{} \textbackslash{} The backslash character \ can not be entered by adding another backslash in front of it (\\ ); this sequence is used for line breaking. For introducing a backslash in math mode, you can use \backslash instead. The 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 [1]. 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.
Basics 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 in mathematical formulae or as accents. We will tackle this issue in Special Characters.
29
LaTeX groups
A group is basically defined by a pair of braces. The range of commands put between braces is limited to them. The \begingroup and \endgroup commands are equivalent to opening brace and closing brace. Example: { \bf This is bold. } This is no longer bold. For some commands it is important to restrict their range of action, and that's where groups come to be very useful.
LaTeX environments
Environments in LaTeX have a role that is quite similar to commands, but they usually have effect on a wider part of the document. Their syntax is: \begin{environmentname} text to be influenced \end{environmentname} Between the \begin and the \end you can put other commands and nested environments. 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
LaTeX commands are case sensitive, and take one of the following two formats: They start with a backslash \ and then have a name consisting of letters only. Command names are terminated by a space, a number or any other "non-letter". They consist of a backslash \ and exactly one non-letter. Some commands need an argument, which has to be given between curly braces { } after the command name. Some commands support optional parameters, which are added after the command name in square brackets [ ] . The general syntax is: \commandname[option1,option2,...]{argument1}{argument2}... Most standard LaTeX commands have a switch equivalent. Switches have no arguments but apply on the rest of the scope, i.e. the current group or environment. A switch should (almost) never be called outside of any scope, otherwise it will apply on the rest of the document. Example: % \emph is a command with argument, \em is a switch. \emph{emphasized text}, this part is normal % Correct {\em emphasized text}, this part is normal % Correct \em emphasized text, this part is normal % Incorrect \em{emphasized text}, this part is normal % Incorrect
Basics
30
Comments
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 multi-line comments for simple workarounds.
\documentclass{article}
\begin{document}
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.
Basics
31
Compilation
Compilation process
The general concept is to transform a plain text document into a publishable format, mosty a DVI, PS or PDF file. This process is called compilation, which is done by an executable file called a compiler. There are two main compilers. tex compiler reads a TeX .tex file and creates a .dvi. pdftex compiler reads a TeX .tex file and creates a .pdf. These compilers are basically used to compile plainTeX, not LaTeX. There is no such LaTeX compiler since LaTeX is just a bunch of macros for TeX. However, there are two executables related to the previous compilers: latex executable calls tex with LaTeX initialization files, reads a LaTeX .tex file and creates a .dvi pdflatex executable calls pdftex with LaTeX initialization files, reads a LaTeX .tex file and creates a .pdf If you compile a plainTeX document with a LaTeX compiler (such as pdflatex) it will work while the opposite is not true: if you try to compile a LaTeX source with a TeX compiler you will get many errors. As a matter of fact, following your operating system latex and pdflatex are simple scripts or symbolic links. Most of the programs should be already within your LaTeX distribution; the others come with w:Ghostscript, which is a free and multi-platform software as well. Here are common programs you expect to find in any LaTeX distribution: dvi2ps converts the .dvi file to .ps (postscript). dvi2pdf converts the .dvi file to .pdf (dvi2pdfm is an improved version). and with Ghostscript: ps2pdf and pdf2ps converts the .ps file to .pdf and vice-versa. When LaTeX was created, the only format it could create was DVI; later PDF support was added by pdflatex. PDF files can be created with both pdflatex and dvipdfm. The output of pdflatex takes direct advantage of modern features of PDF such as hyperlinks and embedded fonts, which are not part of DVI. Passing through DVI imposes limitations of its older format. On the other hand, some packages, such as PSTricks, exploit the process of conversion to DVI, and therefore will not work with pdflatex. Some of those packages embed information in the DVI that doesn't appear when the DVI is viewed, but reemerges when the DVI is converted to another, newer format. You would write your document slightly differently depending on the compiler you are using (latex or pdflatex). But as we will see later it is possible to add a sort of abstraction layer to hide the details of which compiler you're using, while the compiler can handle the translation itself. The following diagram shows the relationships between the LaTeX source code and the formats you can create from it:
Basics
32
The boxed red text represents the file formats, the blue text on the arrows represents the commands you have to use, the small dark green text under the boxes represents the image formats that are supported. Any time you pass through an arrow you lose some information, which might decrease the features of your document. Therefore, you should choose the shortest route to reach your target format. This is probably the most convenient way to obtain an output in your desired format anyway. Starting from a LaTeX source, the best way is to use only latex for a DVI output or pdflatex for a PDF output, converting to PostScript only when it is necessary to print the document. Chapter ../Export To Other Formats/ discusses more about exporting LaTeX source to other file formats.
Basics This means that your source file has been processed and the resulting document is called hello.dvi, which takes up 1 page and 232 bytes of space. Now you may view the DVI file. On Unix with X11 you can type xdvi foo.dvi, on Windows you can use a program called yap (yet another previewer). (Now evince and okular, the standard document viewers for many Linux distributions are able to view DVI files.) This way you created the DVI file, but with the same source file you can create a PDF document. The steps are exactly the same as before, but you have to replace the command latex with pdflatex: 1. Type the command: pdflatex hello (as before, the .tex extension is not required) 2. Various bits of info about LaTeX and its progress will be displayed. If all went well, the last two lines displayed in the console will be: Output written on hello.pdf (1 page, 5548 bytes). Transcript written on hello.log. you can notice that the PDF document is bigger than the DVI, even if it contains exactly the same information. The main differences between the DVI and PDF formats are: DVI needs less disk space and it is faster to create. It does not include the fonts within the document, so if you want the document to be viewed properly on another computer, there must be all the necessary fonts installed. It does not support any interactivity such as hyperlinks or animated images. DVI viewers are not very common, so you can consider using it for previewing your document while typesetting. PDF needs more disk space and it is slower to create, but it includes all the necessary fonts within the document, so you will not have any problem of portability. It supports internal and external hyperlinks. It also supports advanced typographic features: hanging punctuation, font expansion and margin kerning resulting in more flexibility available to the TeX engine and better looking output. Nowadays it is the de facto standard for sharing and publishing documents, so you can consider using it for the final version of your document. About now, you saw you can create both DVI and PDF document from the same source. This is true, but it gets a bit more complicated if you want to introduce images or links. This will be explained in detail in the next chapters, but for now assume you can compile in both DVI and PDF without any problem. Note, in this instance, due to the simplicity of the file, you only need to run the LaTeX command once. However, if you begin to create complex documents, including bibliographies and cross-references, etc, LaTeX needs to be executed multiple times to resolve the references. But this will be discussed in the future when it comes up.
33
Compressed PDF
For a PDF output, you may have noticed that the output PDF file is not always the same size depending on the engine you used to compile the file. So latex dvips ps2pdf will usually be much smaller than pdflatex. So if you want pdflatex features along with a small output file size, you can use the Ghostscript command:
$ gs -dBATCH -dNOPAUSE -q -sDEVICE=pdfwrite -sOutputFile="Compressed.pdf" "Original.pdf"
Files
Picking suitable filenames
Never, ever use directories (folders) or file names that contain spaces. Although your operating system probably supports them, some don't, and they will only cause grief and tears with TeX. Make filenames as short or as long as you wish, but strictly avoid spaces. Stick to lower-case letters without accents (a-z), the digits 0-9, the hyphen (), and 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
Basics operating systems do not distinguish between upper-case and lower-case letters, others do. Therefore it's best not to mix them.
34
Ancillary files
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 content 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 than the current document but a different extension. It stores temporary data into these files and use them for the next compilation. So to have an up-to-date table of contents, you need to compile the document twice. There is no need to re-compile if no section moved. For example, the temporary file for the table of contents data is filename.toc. None of these files contains unrecoverable information. It means you can delete them safely, compiling will regenerate them automatically. When you work with various capabilities of LaTeX (index, glossaries, bibliographies, etc.) you will soon find yourself in a maze of files with various extensions and probably no clue. The following list explains the most common file types you might encounter when working with TeX:
.dvi Device Independent File. This is the main result of a LaTeX compile run with latex. You can look at its content with a DVI previewer program or you can send it to a printer with dvips or a similar application. .pdf Portable Document Format. This is the main result of a LaTeX compile run with pdflatex. You can look at its content or print it with any PDF viewer. .log Gives a detailed account of what happened during the last compiler run. .toc Stores all your section headers. It gets read in for the next compiler run and is used to produce the table of contents. .lof This is like .toc but for the list of figures. .lot And again the same for the list of tables. .idx If your document contains an index. LaTeX stores all the words that go into the index in this file. Process this file with makeindex. .ind The processed .idx file, ready for inclusion into your document on the next compile cycle. .ilg Logfile telling what makeindex did.
Basics
35
.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.
Modular document
See Modular Documents for good recommendations about the way to organize big projects into multiple files.
Working in a team
See chapter ../Collaborative Writing of LaTeX Documents/.
References
[1] http:/ / tex. stackexchange. com/ questions/ 9363/ how-does-one-insert-a-backslash-or-a-tilde-into-latex
36
Common Elements
Document Structure
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Document Structure
37 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] The main point of writing a text is to convey ideas, information, or knowledge to the reader. The reader will understand the text better if these ideas are well-structured, and will see and feel this structure much better if the typographical form reflects the logical and semantic structure of the content. LaTeX is different from other typesetting systems in that you just have to tell it the logical and semantical structure of a text. It then derives the typographical form of the text according to the rules given in the document class file and in various style files. LaTeX allows users to structure their documents with a variety of hierarchical constructs,
38
Global structure
When LaTeX processes an input file, it expects it to follow a certain structure. Thus every input file must contain the commands \documentclass{...} \usepackage{...} \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
Document classes
When processing an input file, LaTeX needs to know the type of document the author wants to create. This is specified with the \documentclass command. It is recommended to put this declaration at the very beginning. \documentclass[options]{class} Here class specifies the type of document to be created. The LaTeX distribution provides additional classes for other documents, including letters and slides. 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:
Document Structure
39
Document Classes
article For articles in scientific journals, presentations, short reports, program documentation, invitations, ...
IEEEtran For articles with the IEEE Transactions format. proc minimal report book slides memoir letter beamer A class for proceedings based on the article class. Is as small as it can get. It only sets a page size and a base font. It is mainly used for debugging purposes. For longer reports containing several chapters, small books, thesis, ... For real books. For slides. The class uses big sans serif letters. For changing sensibly the output of the document. It is based on the book class, but you can create any kind of document with it [1] For writing letters. For writing presentations (see LaTeX/Presentations).
The standard document classes that are a part of LaTeX are built to be fairly generic, which is why they have a lot of options in common. Other classes may have different options (or none at all). Normally, third party classes come with some documentation to let you know. The most common options for the standard document classes are listed in the following table:
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 openright, openany Changes the layout of the document to print in landscape mode. 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. 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.
draft
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}
Document Structure
40
Packages
While writing your document, you will probably find that there are some areas where basic LaTeX cannot solve your problem. If you want to include graphics, colored text or source code from a file into your document, you need to enhance the capabilities of LaTeX. Such enhancements are called packages. Some packages come with the LaTeX base distribution. Others are provided separately. Modern TeX distributions come with a large number of packages pre-installed. Packages are activated with the \usepackage[options]{package} command, where package is the name of the package and options is a list of keywords that trigger special features in the package. For example, to use the color package, which lets you typeset in colors, you would type: \documentclass[11pt,a4paper,oneside]{report} \begin{document} ... \end{document} \usepackage{color}
You can include several package names in one \usepackage command by separating the names with commas, like this: \usepackage{package1,package2,package3} and you can have more than one \usepackage command. Some packages allow optional settings in square brackets. If you use these, you must give the package its own separate \usepackage command, like geometry shown below: \documentclass[11pt,a4paper,oneside]{report} \usepackage{pslatex,palatino,avant,graphicx,color} \usepackage[margin=2cm]{geometry} \begin{document} \title{\color{red}Practical Typesetting} \author{\color{blue}Name\\ Work} \date{\color{green}December 2005} \maketitle \end{document} Many packages can have additional formatting specifications in optional arguments in square brackets, in the same way as geometry does. Read the documentation for the package concerned to find out what can be done. You can pass several options together separated by a comma: \usepackage[option1,option2,option3]{''package_name''}
Document Structure finish the top matter with the \maketitle command, which tells LaTeX that it's complete and it can typeset the title according to the information you have provided and the class (style) you are using. If you omit \maketitle , the titling will never be typeset (unless you write your own). Here is a more complicated example: \title{How to Structure a \LaTeX{} Document} \author{Andrew Roberts\\ School of Computing,\\ University of Leeds,\\ Leeds,\\ United Kingdom,\\ LS2 1HE\\ \texttt{andyr@comp.leeds.ac.uk}} \date{\today} \maketitle as you can see, you can use commands as arguments of \title and the others. The double backslash (\\ ) is the LaTeX command for forced linebreak. LaTeX normally decides by itself where to break lines, and it's usually right, but sometimes you need to cut a line short, like here, and start a new one. If there are two authors separate them with the \and command: \title{Our \maketitle Fun Document} \author{Jane Doe \and John Doe} \date{\today}
41
If you are provided with a class file from a publisher, or if you use the AMS article class (amsart), then you can use several different commands to enter author information. The email address is at the end, and the \texttt commands formats the email address using a mono-spaced font. The built-in command called \today will be replaced with the current date when processed by LaTeX. But you are free to put whatever you want as a date, in no set order. If braces are left empty, then the date is omitted. Using this approach, you can create only basic output whose layout is very hard to change. If you want to create your title freely, see the Title Creation section.
Abstract
As most research papers have an abstract, there are predefined commands for telling LaTeX which part of the content makes up the abstract. This should appear in its logical order, therefore, after the top matter, but before the main sections of the body. This command is available for the document 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
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. \section{Introduction} This section's content... \section{Structure} This section's content... \subsection{Top Matter} This subsection's content... \subsubsection{Article Information} This subsubsection's content... Notice that you do not need to specify section numbers; LaTeX will sort that out for you. Also, for sections, you do not need to markup which content belongs to a given block, using \begin and \end commands. 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.
Document Structure
42
Command
Level -1 0 1 2 3 4 5
Comment not in letters only books and reports not in letters not in letters not in letters not in letters not in letters
All the titles of the sections are added automatically to the table of contents (if you decide to insert one). But if you make manual styling changes to your heading, for example a very long title, or some special line-breaks or unusual font-play, this would appear in the Table of Contents as well, which you almost certainly don't want. LaTeX allows you to give an optional extra version of the heading text which only gets used in the Table of Contents and any running heads, if they are in effect. This optional alternative heading goes in [square brackets] before the curly braces: \section[Effect on staff turnover]{An analysis of the effect of the revised recruitment policies on staff turnover at divisional headquarters} Section numbering Numbering of the sections is performed automatically by LaTeX, so don't bother adding them explicitly, just insert the heading you want between the curly braces. Parts get roman numerals (Part I, Part II, etc.); chapters and sections get decimal numbering like this document, and appendices (which are just a special case of chapters, and share the same structure) are lettered (A, B, C, etc.). You can change the depth to which section numbering occurs, so you can turn it off selectively. By default it is set to 2. If you only want parts, chapters, and sections numbered, not subsections or subsubsections etc., you can change the value of the secnumdepth counter using the \setcounter command, giving the depth level from the previous table. For example, if you want to change it to "1": \setcounter{secnumdepth}{1} A related counter is tocdepth, which specifies what depth to take the Table of Contents to. It can be reset in exactly the same way as secnumdepth. For example: \setcounter{tocdepth}{3} To get an unnumbered section heading which does not go into the Table of Contents, follow the command name with an asterisk before the opening curly brace: \subsection*{Introduction} All the divisional commands from \part* to \subparagraph* have this "starred" version which can be used on special occasions for an unnumbered heading when the setting of secnumdepth would normally mean it would be numbered. If you want the unnumbered section to be in the table of contents anyway, use the \addcontentsline command like this: \section*{Introduction} \addcontentsline{toc}{section}{Introduction}
Document Structure Note that if you use PDF bookmarks you will need to add a phantom section so that bookmark will lead to the correct place in the document. The \phantomsection command is defined in the hyperref package, and is implemented normally as follows: \phantomsection \section*{Introduction} \addcontentsline{toc}{section}{Introduction}
43
For chapters you will also need to clear the page (this will also correct page numbering in the ToC): \cleardoublepage \phantomsection \addcontentsline{toc}{chapter}{Bibliography} \bibliographystyle{unsrt} \bibliography{my_bib_file} The value where the section numbering starts from can be set with the following command: \setcounter{section}{4} The next section after this command will now be numbered 5. For more details on counters, see the dedicated chapter. Section number style See Counters.
Ordinary paragraphs
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
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):
44
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 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{Epilog} \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 [2], doc [3]).
Book structure
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 macro to change the formatting of some places of the document. We will give you some advices on how to use them properly.[4] \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, since they will be number 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.
Document Structure 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.
45
Page order
This is one traditional page order for books. Frontmatter 1. 2. 3. 4. 5. 6. 7. 8. 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 1. Main topic Appendix 1. Some subordinate chapters Backmatter 1. Bibliography 2. Glossary / Index
In the above code sample, the second page of the introduction will have TABLE OF CONTENTS printed in the header. This is because the starred \chapter* command does not set the leftmark -- see Page Layout. And it will not be printed in the table of contents either. The trick is to set the leftmark and the TOC manually: \chapter*{Introduction} \markboth{\MakeUppercase{Introduction}}{} \addcontentsline{toc}{chapter}{Introduction} % ... TABLE OF CONTENTS is traditionally printed both left and right, but here we print it like other chapters, only right on even pages. To make it more convenient, you might use a macro: \newcommand\intro[1]{ \chapter*{#1} \markboth{\MakeUppercase{#1}}{} \addcontentsline{toc}{chapter}{#1} } %% ... \intro{Introduction}
Document Structure
46
Special pages
Comprehensive papers often feature special pages at the end, like indices, glossaries and bibliographies. Since this is a quite complex topic, we will give you details in the dedicated part Special Pages.
Bibliography
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 [5] and then link them via a command to your current document and use a Bibtex style [6] 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.
Text Formatting
LaTeX
Text Formatting
47 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Text Formatting
48 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] This section will guide you through the formatting techniques of the text. Formatting tends to refer to most things to do with appearance, so it makes the list of possible topics quite eclectic: text style, spacing, etc. If formatting may also refer to paragraphs and to the page layout, we will focus on the customization of words and sentences for now. A lot of formatting techniques are required to differentiate certain elements from the rest of the text. It is often necessary to add emphasis to key words or phrases. Footnotes are useful for providing extra information or clarification without interrupting the main flow of text. So, for these reasons, formatting is very important. However,
Text Formatting it is also very easy to abuse, and a document that has been over-done can look and read worse than one with none at all. LaTeX is so flexible that we will actually only skim the surface, as you can have much more control over the presentation of your document if you wish. Having said that, one of the purposes of LaTeX is to take away the stress of having to deal with the physical presentation yourself, so you need not get too carried away!
49
Spacing
Line Spacing
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. 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} %\setstretch{1.1} %\singlespacing \onehalfspacing %\doublespacing
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}
Non-breaking spaces
This essential feature is a bit unknown to newcomers, although it is available on most WYSIWYG document processors. A non-breaking space between two tokens (e.g. words, punctuation marks) prevents the processors from inserting a line break between them. Besides a non-breaking space cannot be enlarged. It is very important for a consistent reading. LaTeX uses the '~' symbol as a non-breaking space. You would usually use non-breaking spaces for punctuation marks in some languages, for units and currencies, for initials, etc. In French typography, you would put a non-breaking space before all two-parts punctuation marks. Examples: D.~\textsc{Knuth} 50~
Text Formatting \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 in front of a space generates a space that will not be enlarged. A tilde ~ character generates a non-breaking space. The command \@ in front of a period specifies that this period terminates a sentence even when it follows an uppercase letter. (If you are using \frenchspacing , then none of these exceptions need be specified.)
50
Stretched spaces
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
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
LaTeX hyphenates words whenever necessary. Hyphenation rules will vary for different languages. LaTeX only supports english by default, so if you want to have correct hyphenation rules for your desired language, see Internationalization. If the hyphenation algorithm does not find the correct hyphenation points, you can remedy the situation by using the following commands to tell TeX about the exception. The command \hyphenation{word list} causes the words listed in the argument to be hyphenated only at the points marked by -. The argument of the command should only contain words built from normal letters, or rather characters that are considered to be normal letters by LaTeX. It is known that the hyphenation algorithm does not find all correct American English hyphenation points for several words. A log of known exceptions is published periodically in the TUGboat journal. (See a 2008 list: http://www.tug.org/TUGboat/Articles/tb29-2/tb92hyf.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
Text Formatting babel. The example below will allow hyphenation to be hyphenated as well as Hyphenation, and it prevents FORTRAN, Fortran and fortran from being hyphenated at all. No special characters or symbols are allowed in the argument. Example: \hyphenation{FORTRAN Hy-phen-a-tion} The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word. This command is especially useful for words containing special characters (e.g., accented characters), because LaTeX does not automatically hyphenate words containing special characters. \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.
51
Text Formatting
52
Quote-marks
LaTeX treats left and right quotes as different entities. For single quotes, ` (on American keyboards, this symbol is found on the tilde key (adjacent to the number 1 key on most) gives a left quote mark, and ' is the right. For double quotes, simply double the symbols, and LaTeX will interpret them accordingly. (Don't use the " for right double quotes: when the babel package is used for some languages (e.g. German), the " is redefined to produce an umlaut accent; using " for right double quotes will either lead to bad spacing or it being used to produce an umlaut). On British keyboards, ' ` ' is left of the ' 1 ' key and shares the key with ' ', and sometimes ' ' or ' | '. The apostrophe (') key is to the right of the colon/semicolon key and shares it with the ' @ ' symbol. To `quote' in LaTeX To ``quote'' in LaTeX To ``quote" in LaTeX To ,,quote'' in LaTeX ``Please press the `x' key.'' ,,Prosz, nacinij klawisz <<x>>''. 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 multi-lingual 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.
Text Formatting
53
Ligatures
Some letter combinations are typeset not just by setting the different letters one after the other, but by actually using special symbols (like ""), called ligatures. Ligatures can be prohibited by inserting {} or, if this does not work, {\kern0pt} between the two letters in question. This might be necessary with words built from two words. Here is an example: \Large Not shelfful\\ but shelf{}ful
Some tools are unable to perform search in documents that contain ligatures (a search for "finally" wouldn't find the string "nally"). If one desires, for greater accessibility, to disable ligatures altogether in the whole document, the \DisableLigatures from the microtype package [2] can be used: \usepackage{microtype} \DisableLigatures{encoding = *, family = *} Note that this will also disable ligatures such as "--" to "", "---" to "", etc. If you are using XeLaTeX and OpenType fonts, the fontspec package allows for standard ligatures to be turned off as well as fancy swash ligatures to be turned on. Another solution is to use the cmap package, which will help the reader to interpret the ligatures: \usepackage[resetfonts]{cmap}
Slash marks
The normal typesetting of the / character in LaTeX does not allow following characters to be "broken" on to new lines, which often create "overfull" errors in output (where letters push off the margin). Words that use slash marks, such as "input/output" should be typeset as "input\slash output ", which allow the line to "break" after the slash mark (if needed). The use of the / character in LaTeX should be restricted to units, such as "mm/year ", which should not be broken over multiple lines.
Fonts
To change the font family, emphasize text, and other font-related issues, see Fonts.
Formatting macros
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, its occupied by \oops{machines} of unknown origin and purpose.
Do not enter this room, its 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.
54
Text Formatting
55
Text Formatting Use \hyp{} macro from hyphenat package instead of hyphen if you want LaTeX to break compound words between lines.
56
Ellipsis ()
A sequence of three dots is known as an ellipsis, which is commonly used to indicate omitted text. On a typewriter, a comma or a period takes the same amount of space as any other letter. In book printing, these characters occupy only a little space and are set very close to the preceding letter. Therefore, you cannot enter ellipsis by just typing three dots, as the spacing would be wrong. Instead, there is a special command for these dots. It is called \ldots : Not like this ... but like this:\\ New York, Tokyo, Budapest, \ldots Alternatively, you can use the \textellipsis command which allows the spacing between the dots to vary.
Ready-made strings
There are some very simple LaTeX commands for typesetting special text strings:
[6] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ mhchem/
This page uses material from Andy Roberts' Getting to grips with LaTeX (http:/ / www. andy-roberts. net/ writing/ latex) with permission from the author.
Paragraph Formatting
57
Paragraph Formatting
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Paragraph Formatting
58 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Altering the paragraph formatting is not often required, especially in academic writing. However, it is useful to know, and applications tend to be for formatting text in floats, or other more exotic documents.
Paragraph Formatting
59
Paragraph alignment
Paragraphs in LaTeX are usually fully justified, i.e. flush with both the left and right margins. For whatever reason, should you wish to alter the justification of a paragraph, there are three environments at hand, and also LaTeX command equivalents.
Alignment Left justified Environment flushleft Command
All text between the \begin and \end of the specified environment will be justified appropriately. The commands listed are for use within other environments. For example, p (paragraph) columns in tabular.
Paragraph Formatting 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 .
60
Line spacing
To change line spacing in the whole document use the command \linespread covered in Text Formatting. To change line spacing in specific environments do the following: 1. Add \usepackage{setspace} to the document preamble. 2. This then provides the following environments to use within your document: doublespace - all lines are double spaced. onehalfspace - line spacing set to one-and-half spacing. singlespace - normal line spacing. 3. To change line spacing to custom values, use the command \setstretch{baselinestretch} in the preamble to change line spacing for the whole document or use the environment \begin{spacing}{2.5} ... \end{spacing} to change the line spacing to whatever is greater, the document-wide or environment-wide one. After declaring the package in the preamble the use of the command \singlespacing , \doublespacing , or \onehalfspacing will specify the line spacing for all sections and paragraphs until another command is used. See the section on customizing lists for information on how to change the line spacing in lists.
Paragraph Formatting
61
Manual breaks
LaTeX takes care of the formatting, breaks included. You should avoid manual breaking as much as possible, or it could lead to very bad formatting. Controlling the breaks should be reserved to macro and package writers. Here follows a quick reference. \newline \\
Breaks the line at the point of the command. Breaks the line at the point of the command; it is usually a shorter version of the previous command, but LaTeX sometimes redefines it for several environments. This command also features the vertical space as optional parameter. Breaks the line at the point of the command and additionally prohibits a page break after the forced line break. This command also features the vertical space as optional parameter. Breaks the line at the point of the command. The number you provide as an argument represents the priority of the command in a range from 0 (it will be easily ignored) to 4 (do it anyway). LaTeX will try to produce the best line breaks possible. If it cannot, it will decide whether including the linebreak or not according to the priority you have provided. Breaks the line without filling the current line. This will result in an underful badness if you do not fill the line yourself, i.e....\hfill\break ... . Actually \hfill\break produces the same as \newline and \\ . Starts a new paragraph. It is an horizontal mode command, so you can only use it in a paragraph.
\\* \linebreak[number]
\break
(TeX)
\par
(TeX)
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
Verbatim text
There are several ways to introduce text that won't be interpreted by the compiler. If you use the verbatim environment, everything input between the begin and end commands are processed as if by a typewriter. All spaces and new lines are reproduced as given, and the text is displayed in an appropriate fixed-width font. Any LaTeX command will be ignored and handled as plain text. 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 $ .
Paragraph Formatting When using \textbf{} inside the allttC 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. Typesetting URLs One of either the hyperref or url packages provides the \url command, which properly typesets URLs, for example: Go to \url{http://www.uni.edu/~myname/best-website-ever.html} for my website. will show this URL exactly as typed (similar to the \verb command), but the \url command also performs a hyphenless break at punctuation characters (only in PDFLaTeX, not in plain LaTeX+ dvips). It was designed for Web URLs, so it understands their syntax and will never break mid-way through an unpunctuated word, only at slashes and full stops. Bear in mind, however, that spaces are forbidden in URLs, so using spaces in \url arguments will fail, as will using other non-URL-valid characters. When using this command through the hyperref package, the URL is "clickable" in the PDF document, whereas it is not linked to the web when using only the url package. Also when using the hyperref package, to remove the border placed around a URL, insert pdfborder = {0 0 0 0} inside the \hypersetup{} . (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 This is also an extension of the verbatim environment provided by the moreverb package. The extra functionality it provides is that it can add line numbers along side the text. The command: \begin{listing}[step]{first line} . The mandatory first line argument is for specifying which line the numbering shall commence. The optional step is the step between numbered lines (the default is 1, which means every line will be numbered). To use this environment, remember to add \usepackage{moreverb} to the document preamble.
62
Paragraph Formatting
63
Multi-line comments
As we have seen, the only way LaTeX allows you to add comments is by using the special character % , that will comment out all the rest of the line after itself. This approach is really time-consuming if you want to insert long comments or just comment out a part of your document that you want to improve later, 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 wont 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. 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).
But it won't show.
Quoting text
LaTeX provides several environments for quoting text; they have small differences and they are aimed for different types of quotations. All of them are indented on either margin, and you will need to add your own quotation marks if you want them. The provided environments are: quote for a short quotation, or a series of small quotes, separated by blank lines. quotation for use with longer 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 \\ .
Paragraph Formatting
64
Abstracts
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.
References
[1] http:/ / www. andy-roberts. net/ writing/ latex
Colors
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Colors
65 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Adding colors to your text is supported by the color [1] package. Using this package, you can set the color of the font of the text, and set the background color of the page. You can use one of the predefined colors such as white, red, or yellow, or you can define your own named colors. It's also possible to color formulas in math-environments.
Colors
66
Colors
67
Predefined colors
The predefined color names are white, black, red, green, blue, cyan, magenta, 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
Colors
68
Salmon Sepia SpringGreen TealBlue Turquoise VioletRed WildStrawberry YellowGreen SeaGreen SkyBlue Tan Thistle Violet White Yellow YellowOrange
Place
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
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 and cmyk. color-spec is the description of the color
Color Models
Among the models you can use to describe the color are the following (several more are described in the xcolor manual [3]):
Color Models
Model gray Description Shades of gray Color Specification Example
Just one number between 0 (black) and 1 (white), so 0.95 will \definecolor{light-gray}{gray}{0.95} be very light gray, 0.30 will be dark gray. Three numbers given in the form red,green,blue; the quantity of each color is represented with a number between 0 and 1. Three numbers given in the form red,green,blue; the quantity of each color is represented with a number between 0 and 255. Six hexadecimal numbers given in the form RRGGBB; similar to what is used in HTML. 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}{rgb}{1,0.5,0}
rgb
RGB
\definecolor{orange}{RGB}{255,127,0}
HTML
\definecolor{orange}{HTML}{FF7F00}
cmyk
\definecolor{orange}{cmyk}{0,0.5,1,0}
Colors
69
Examples
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, 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, (30*0.3) percent black and 70 percent green. \color{blue!20} \color{blue!20!black} \color{blue!20!black!30!green} xcolor also feature a handy command to define colors from color mixes: \colorlet{notgreen}{blue!50!yellow}
Capturing colors
You may want to use colors that appear on other document, web pages, pictures, etc. On Unix systems, you can use the small gcolor2 tool which will let you capture any color on screen. When surfing on the web, you can get hexadecimal code for each color on a web page using the colorzilla extension to Firefox.
Sources
The xcolor manual [3]
References
[1] http:/ / www. ctan. org/ pkg/ color [2] http:/ / www. ctan. org/ pkg/ xcolor [3] http:/ / mirror. ctan. org/ macros/ latex/ contrib/ xcolor/ xcolor. pdf
Fonts
70
Fonts
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Fonts
71 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Fonts are a complex topic. For common document, only Font families, Emphasizing text, and Font encoding are really needed. The other sections are more useful to macro writers or for very specific needs.
Fonts
72
Introduction
The digital fonts have a long and intricate history. See Adobe Font Metrics for some more details. Originally TeX was conceived to use its own font system, MetaFont, designed by D. Knuth. The default font family for TeX and friends is called Computer Modern. These high quality fonts are scalable, and have a wide range of typographical fine tuning capabilities. Standard tex compilers will let you use other fonts. There are many different font types, such as PostScript Type1/Type3 fonts and bitmap fonts. Type1 are outline fonts (vector graphics) which are commonly used by pdftex. Bitmap fonts are raster graphics, and usually have very poor quality, which can easily be seen when zooming or printing a document. Type3 is a superset of Type1 and has more functionalities from Postscript, such as embedding raster graphics. In the TeX world, Type3 fonts are often used to embed bitmap fonts. It should be noticed that fonts get generated the first time they are required, hence the long compilation time. However, MetaFont is internally a quite complex font system, and the most popular font systems as of this day are Truetype font (ttf) and OpenType font (otf). With modern TeX compilers such as xetex and luatex it is possible to make use of such fonts in LaTeX documents. If you want/have to stick with the standard compilers, the aforementioned font types must first be converted and made available to LaTeX (e.g. converted to Type1 fonts). The external links section below has some useful resources. In LaTeX, there are many ways to specify and control fonts. It is a very complex matter in typography.
Font families
There are many font families e.g. Computer Modern, Times, Arial and Courier. Those families can be grouped into three main categories: roman (rm) or serif, sans serif (sf) and monospace (tt) (see Typeface for more details). Each font family comes with the default design which falls into one of those categories; however, it is interchangeable among them. Computer Modern Roman is the default font family for LaTeX. Fonts in each family also have different properties (size, shape, weight, etc.). Families are meant to be consistent, so it is highly discouraged to change fonts individually rather than the whole family. The three families are defined by their respective variables: \rmdefault \sfdefault \ttdefault The default family is contained in the \familydefault variable, and it is meant to have one of the three aforementionned variable as value. The default is defined like the following assignment: \renewcommand*{\familydefault}{\sfdefault} This will turn all the part of the document using the default font to the default sans serif, which is Computer Modern Sans Serif if you did not change the default font. Changing font families usually works in two steps: 1. First specify which family you want to change (rm, sf or tt). 2. Second specify the new default family if it is not rm. Mathematical fonts is a more complex matter. Fonts may come with a package that will take care of defining all three families plus the math fonts. You can do it by yourself, in which case you do not have to load any package. Below is an example[1] that demonstrates how to change a specific family.
Fonts
73
% Default font (\familydefault = \rmdefault = Computer Modern Roman) Lorem ipsum dolor sit amet, consectitur adipiscing elit. % Palatino font (ppl must be installed). \renewcommand*\rmdefault{ppl} Lorem ipsum dolor sit amet, consectitur adipiscing elit. % Iwona font (iwona must be installed). \renewcommand*\rmdefault{iwona} Lorem ipsum dolor sit amet, consectitur adipiscing elit. The three default family font variables and the \familydefault variable should not be confused with their respective switch: \normalfont \rmfamily \sffamily \ttfamily
Emphasizing Text
In order to add some emphasis to a word or a phrase, the simplest (and the most correct) way is to use the \emph{text} command. I want to \emph{emphasize} a word. Note that the \emph command is dynamic: if you emphasize a word which is already in an emphasized sentence, it will be reverted to the upright font. \emph{In this emphasized sentence, there is an emphasized \emph{word} which looks upright.}
In this emphasized sentence, there is an emphasized word which looks upright.
Font encoding
A character is a sequence of bytes, and should not be confused with its representation, the glyph, which is what the reader sees. So the character 'a' has different representations following the used font, for example the upright version, the italic version, various weights and heights, and so on. Upon compilation, tex will have to choose the right font glyph for every character. This is what is called font encoding. The default LaTeX font encoding is OT1, the encoding of the original Computer Modern TeX text fonts. It contains only 128 characters, many from ASCII, but leaving out some others and including a number that are not in ASCII. When accented characters are required, TeX creates them by combining a normal character with an accent. While the resulting output looks perfect, this approach has some caveats. It stops the automatic hyphenation from working inside words containing accented characters. Searches for words with accents in PDFs will fail. Extracting ('e.g.' copy paste) the umlaut '' via a PDF viewer actually extracts the two characters '"A '. Besides, some of Latin letters could not be created by combining a normal character with an accent, to say nothing about letters of non-Latin alphabets, such as Greek or Cyrillic.
To overcome these shortcomings, several 8-bit CM-like font sets were created. Extended Cork (EC) fonts in T1 encoding contains letters and punctuation characters for most of the European languages based on Latin script. The LH font set contains letters necessary to typeset documents in languages using Cyrillic script. Because of the large number of Cyrillic glyphs, they are arranged into four font encodingsT2A, 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
Fonts CM families in all weights, shapes, and optically scaled font sizes. All this is not possible with OT1, that's why you may want to change the font encoding of your document. Note that changing the font encoding will have some requirements over the fonts being used. The default Computer Modern font does not support T1. You will need Computer Modern Super (cm-super) or Latin Modern (lmodern), which are Computer Modern-like fonts with T1 support. If you have none of these, it is quite frequent (depends on your TeX installation) that tex chooses a Type3 font such as the Type3 EC, which is a bitmap font. Bitmap fonts look rather ugly when zoomed or printed. The fontenc package tells LaTeX what font encoding to use. Font encoding is set with: \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.
74
Font styles
Each family has its own font characteristics (such as italic and bold), also known as font styles, or font properties. Font styles are usually implemented with different font files. So it is possible to build a new font family by specifying the font styles of different font families.
Shapes
The following table lists the commands you will need to access the typical font shapes:
LaTeX command Equivalent to Output style document font family emphasis roman font family sans serif font family teletypefont family upright shape italic shape slanted shape A skewed version of the normal typeface (similar to, but slightly different from, italics). This is a fixed-width or monospace font. Remarks This is the default or normal font.
\textnormal{...} {\normalfont ...} \emph{...} \textrm{...} \textsf{...} \texttt{...} \textup{...} \textit{...} \textsl{...} \textsc{...} \uppercase{...} {\em ...} {\rmfamily ...} {\sffamily ...} {\ttfamily ...} {\upshape ...} {\itshape ...} {\slshape ...} {\scshape ...}
Typically italics.
Small Capitals uppercase (all caps) Also \lowercase . There are some caveats, though; see [2] here .
Fonts
\textbf{...} \textmd{...}
The commands in column two are not entirely equivalent to the commands in column one: They do not correct spacing after the selected font style has ended. The commands in column one are therefore in general recommended. You may have noticed the absence of underline. This is because underlining is not recommended for typographic reasons (it weighs the text down). You should use emph instead. However underlining text provides a useful extra form of emphasis during the editing process, for example to draw attention to changes. Although underlining is available via the \underline{...} command, text underlined in this way will not break properly. This functionality has to be added with the ulem (underline emphasis) package. Stick \usepackage{ulem} in your preamble. By default, this overrides the \emph command with the underline rather than the italic style. It is unlikely that you wish this to be the desired effect, so it is better to stop ulem taking over \emph and simply call the underline command as and when it is needed. To restore the usual \emph formatting, add \normalem straight after the document environment begins. Alternatively, use \usepackage[normalem]{ulem} . To underline, use \uline{...} . To add a wavy underline, use \uwave{...} . For a strike-out (strikethrough), use \sout{...} . For a slash through each individual character \xout{...} . Some font styles are not compatible one with the other. But some extra packages will fill this hole. For bold small capitals, you might want to use: \usepackage{bold-extra} % ... \textsc{ \textbf{This is bold small capitals} }
Sizing text
To apply different font sizes, simply follow the commands on this table:
These commands change the size within a given scope, so for instance {\Large some words} will change the size of only some words , and does not affect the font in the rest of the document. It will work for most parts of the text. {\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{...}
Fonts which delimits the unit. The default for \normalsize is 10point (option 10pt ), but it may differ for some Document Styles or their options. The actual size produced by these commands also depends on the Document Style and, in some styles, more than one of these size commands may produce the same actual size. Note that the font size definitions are set by the document class. Depending on the document style the actual font size may differ from that listed above. And not every document class has unique sizes for all 10 size commands.
76
\footnotesize 8.50012 \small \normalsize \large \Large \LARGE \huge \Huge 9.24994
10.00002 8.50012
10.00002 10.95003
10.00002 10.95003 11.74988 10.00002 10.95003 11.74988 24.88382 10.00002 10.95003 11.74988 11.74988 11.74988 14.09984 10.95003 11.74988 14.09984 29.86258 11.74988 11.74988 14.09984 14.09984 14.09984 15.84985 11.74988 14.09984 15.84985 35.82510 14.09984 14.09984 16.24988 15.84985 15.84985 19.02350 14.09984 15.84985 19.02350 43.00012 16.24988 16.24988 19.50362 19.02350 19.02350 22.82086 15.84985 19.02350 22.82086 51.60014 19.50362 19.50362 23.39682 22.82086 22.82086 22.82086 19.02350 22.82086 22.82086 51.60014 23.39682 23.39682 23.39682
As a technical note, points in TeX follow the standard American point size in which 1 pt is approximately 0.3513_6 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.352_7 mm while the standard European point size (known as the Didot point) had 1 pt equal to approximately 0.37597151 mm (see: point (typography)).
Fonts { \fontencoding{T1}\fontfamily{anttlc}\fontseries{m}\fontshape{n}\selectfont Some text in anttlc... } The default values are stored in \encodingdefault , \familydefault , \seriesdefault and \shapedefault . Setting back the default font properties can be done with \fontencoding{\encodingdefault} \fontfamily{\familydefault} \fontseries{\seriesdefault} \fontshape{\shapedefault} \selectfont For short, you can use the \usefont{<encoding>}{<family>}{<series>}{<shape>} command. \usefont{T1}{cmr}{m}{n} % Computer Modern Roman (TeX default) in T1 encoding. May lead to bad text quality if you do not have cm-super installed. \usefont{T1}{phv}{m}{sc} % phv family (sans serif) medium small capitals. \usefont{T1}{ptm}{b}{it} % ptm family bold italic \usefont{U}{pzd}{m}{n} % ...
77
Finding fonts
You will find a huge font directory along examples and configurations at TUG Font Catalogue [3].
Fonts Then compile the document with xelatex or lualatex. Note that you can only generate .pdf files, and that you need a sufficiently new TeX distribution (TeX Live 2009 should work for XeTeX and Tex Live 2010 for LuaTeX). Also you should not load the inputenc or fontenc package. To make your document support both pdflatex and xelatex you can use the \ifxetex macro from the ifxetex [5] package. \documentclass{article} \usepackage{ifxetex} \ifxetex \usepackage{fontspec} \usepackage{xunicode} \defaultfontfeatures{Mapping=tex-text} % To support LaTeX quoting style \setromanfont{Hoefler Text} \else \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \fi \begin{document} Lorem ipsum... \end{document}
78
Useful websites
The Latex Font Catalogue [3] LaTeX font commands [6] How to change fonts in Latex [7] Understanding the world of TEX fonts and mastering the basics of fontinst [8] Font installation the shallow way [9] "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"
References
[1] found at the Google discussion group latexlovers [2] http:/ / www. tex. ac. uk/ cgi-bin/ texfaq2html?label=casechange [3] http:/ / www. tug. dk/ FontCatalogue/ [4] http:/ / www. ctan. org/ tex-archive/ help/ Catalogue/ entries/ fontspec. html [5] http:/ / www. ctan. org/ tex-archive/ macros/ generic/ ifxetex/ [6] http:/ / www. cl. cam. ac. uk/ ~rf10/ pstex/ latexcommands. htm [7] http:/ / www. ee. iitb. ac. in/ ~trivedi/ LatexHelp/ latexfont. htm [8] ftp:/ / tug. ctan. org/ tex-archive/ fonts/ utilities/ fontinst/ doc/ talks/ et99-font-tutorial. pdf [9] http:/ / www. tug. org/ TUGboat/ Articles/ tb27-1/ tb86kroonenberg-fonts. pdf [10] http:/ / c. caignaert. free. fr/ Install-ttf-Font. pdf [11] http:/ / www. tex. ac. uk/ ctan/ support/ installfont/ installfont. pdf [12] http:/ / latex. josef-kleber. de/ download/ installfont-tl [13] http:/ / xpt. sourceforge. net/ techdocs/ language/ latex/ latex33-LaTeXAndTrueTypeFont
Fonts
[14] http:/ / fachschaft. physik. uni-greifswald. de/ ~stitch/ ttf. html [15] http:/ / william. famille-blum. org/ software/ latexttf/ index. html [16] http:/ / www. radamir. com/ tex/ ttf-tex. htm
79
List Structures
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
List Structures
80 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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
81
List Structures
Lists often appear in documents, especially academic, as their purpose is often to present information in a clear and concise fashion. List structures in LaTeX are simply environments which essentially come in three flavors: itemize, enumerate and description. All lists follow the basic format: \begin{list_type} \item The third\ldots \end{list_type} first item \item The second item \item The
All three of these types of lists can have multiple paragraphs per item: just type the additional paragraphs in the normal way, with a blank line between each. So long as they are still contained within the enclosing environment, they will automatically be indented to follow underneath their item.
Itemize
This environment is for your standard bulleted list of items. \begin{itemize} \item The first item \item The second item \item The third\ldots \end{itemize}
Enumerate
The enumerate environment is for ordered lists, where by default, each item is numbered sequentially. \begin{enumerate} \item The first item \item The second item \item The third\ldots \end{enumerate}
Description
The description environment is slightly different. You can specify the item label by passing it as an optional argument (although optional, it would look odd if you didn't include it!). Ideal for a series of definitions, such as a glossary. \begin{description} \item[First] The first item \item[Second] The second item \item[Third] The third\ldots \end{description} Sometimes you want a description where the text begins on a new line. This cannot easily be done with \\ . The trick is to use \hfill . \begin{description} \item[First] \hfill \\ The first item \item[Second] \hfill \\ The second item \item[Third] \hfill \\ The third\ldots \end{description}
List Structures
82
Nested lists
LaTeX will happily allow you to insert a list environment into an existing one (up to a depth of four -- if you need more than four, use the easylist package). Simply begin the appropriate environment at the desired point within the current list. Latex will sort out the layout and any numbering for you. \begin{enumerate} \item The first item \begin{enumerate} \item Nested item 1 \item Nested item 2 \end{enumerate} \item The second item \item The third etc \ldots \end{enumerate}
Customizing lists
Customizing LaTeX is outside the beginners' domain. While not necessarily difficult in itself, because beginners are already overwhelmed with the array of commands and environments, moving on to more advanced topics runs the risk of confusion. However, since the tutorial aims at being complete, we shall still include a brief guide on customizing lists. Feel free to skip! Note that in the following when \renewcommand is used it must appear after the \begin{document} instruction so the changes made are taken into account. This is needed for both enumerated and itemized lists. Also beware of the spaces in the label definitions. It is a common error!
Line spacing
As you may have noticed, in standard LaTeX document classes, the vertical spacing between items, and above and below the lists as a whole, is more than between paragraphs: it may look odd if the descriptions are too short. Using packages If you want tightly-packed lists, use the mdwlist package (included in the mdwtools bundle), which provides compact, "starred" versions of the previous environments, i.e. itemize* , enumerate* and description* . They work exactly in the same way, but the output is more compact. Other packages providing compacted lists are paralist and enumitem. Alternatively, use the memoir class and with \tightlists . Customizing manually Inside lists you can redefine some length/dimension variables of LaTeX, for example using: \begin{itemize} \itemsep1pt second item \end{itemize} \parskip0pt \parsep0pt \item first item \item
Alternatively, to create a unified look in your document you can define your own enumerate environment: \newenvironment{my_enumerate}{ \begin{enumerate} \setlength{\itemsep}{1pt} \setlength{\parskip}{0pt} \setlength{\parsep}{0pt} }{ \end{enumerate} } Another approach is to redefine the \item command globally. \newlength{\wideitemsep} \setlength{\wideitemsep}{.5\itemsep} \addtolength{\wideitemsep}{-7pt} \let\olditem\item \renewcommand{\item}{\setlength{\itemsep}{\wideitemsep}\olditem}
List Structures
83
List Structures \renewcommand{\labelitemi}{$\star$} Itemized list with tightly set items, that is with no vertical space between two consecutive items, can be created as follows. \begin{itemize} \setlength{\itemsep}{0cm}% \setlength{\parskip}{0cm}% Item opening the list \item Item tightly following \end{itemize} \item
84
Inline lists
Inline lists are a special case as they require the use of the paralist package which provides the inparaenum environment (with an optional formatting specification in square brackets): \usepackage{paralist} % ... \begin{document} \textbf{\itshape Inline lists}, which are sequential in nature, just like enumerated lists, but are \begin{inparaenum}[\itshape a\upshape)] \item formatted within their paragraph; \item usually labelled with letters; and \item usually have the final item prefixed with `and' or `or', \end{inparaenum} like this example. ... To change the styles of the counter, tokens A, a, I, i, and 1 can be used in the optional argument to produce the counter with one of the styles \Alph , \alph , \Roman , \roman and \arabic . For example: \begin{inparaenum}[(i)] produces the labels (i), (ii), (iii) ... Other packages providing inline lists are shortlst and enumitem.
Easylist package
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} \end{easylist} & Main item~: && Sub item. && Another sub item.
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.
List Structures The Style parameter sets the style of counters and text, the Style* parameter sets the sytle 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 {{{1}}} 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 Blah Blah Blah Blah
85
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. Currently easylist does not work with Beamer.
List Structures
86
Special Characters
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Special Characters
87 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] In this chapter we will tackle matters related to input encoding, typesetting diacritics and special characters. In the following document, we will refer to special characters for all symbols other than A-Za-z0-9 and english punctuation marks. This chapter is tightly linked with the font encoding issue. You should have a look at Fonts on the topic. Some languages usually need a dedicated input system to ease document writing. This is the case for Arabic, Chinese, Japanese, Korean and others. This specific matter will be tackled in Internationalization.
Special Characters 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.
88
Input encoding
A technical matter
Most of the modern computer systems allow you to input letters of national alphabets directly from the keyboard. If you tried to input these special characters in your LaTeX source file and compiled it, you may have noticed that they do not get printed at all. A LaTeX source document is a plain text file. A computer stores data in a binary format, that is a sequence of bits (0 and 1). To display a plain text file, we need a code which tells which sequence of bits corresponds to which sequence of characters. This association is called input encoding, character encoding, or more informally charset. For historical reasons, there are many different input encodings. There is an attempt to unify all the encoding with a specification that contains all existent symbols that are known from human history. This specification is Unicode. It only defines code points, which is a number for a symbol, but not the way symbols are reprensented in binary value. For that, unicode encodings are in charge. There is also several unicode encodings available, UTF-8 being one of them. The ASCII encoding is an encoding which defines 128 characters on 7 bits. Its widespread use has lead the vast majority of encodings to have backward compatibility with ASCII, by defining the first 128 characters the same way. The other characters are added using more bits (8 or more). This is actually a big issue, since if you do not use the right encoding to display a file, it will show weird characters. What most programs try to do is guess statistically the encoding by analyzing the frequent sequences of bits. Sadly, it is not 100% safe. Some text editors may not bother guessing the encoding and will just use the OS default encoding. You should consider that other people might not be able to display directly your input files on their computer, because the default encoding for text file is different. It does not mean that the user cannot use another encoding, besides the default one, only that it has to be configured. For example, the German umlaut on OS/2 is encoded as 132, with Latin1 it is encoded as 228, while in Cyrillic encoding cp1251 this letter does not exist at all. Therefore you should consider encoding with care. The following table shows the default encodings for some operating systems.
Operating system Default Encodings Western Latin Modern Unices (*BSD, Mac OS X, GNU/Linux) utf-8 Mac (before OS X) Unix (Old) Windows DOS, OS/2 applemac latin1 ansinew, cp1252 cp850 Cyrillic utf-8 maccyr koi8-ru cp1251 cp866nav
UTF-8 and Latin1 are not compatible. It means that if you try to open a Latin1-encoded file using a UTF-8 decoding, it will display odd symbols only if you used accents in it, since both encoding are ASCII superset they encode the classic letters the same way. There aren't many advantages in using Latin1 over UTF-8, which is technically superior. UTF-8 is also becoming the most widely used encoding (on the Web, in modern Unices, etc.).
Special Characters
89
In the following we will assume you want to use UTF-8. There are some important steps to specify encoding. Make sure your text editor decodes the file in UTF-8. Make sure it save 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 package tells LaTeX what the text encoding format of your .tex files is.
Special Characters
90
Escaped codes
In addition to direct UTF-8 input, LaTeX supports the composition of special characters. This is convenient if your keyboard lacks some desired accents and other diacritics. The following accents may be placed on letters. Although 'o' letter is used in most of the examples, the accents may be placed on any letter. Accents may even be placed above a "missing" letter; for example, \~{} produces a tilde over a blank space. The following commands may be used only in paragraph (default) or LR (left-right) mode.
LaTeX command Sample Description grave accent acute accent circumflex umlaut, trema or dieresis long Hungarian umlaut (double acute) tilde cedilla ogonek l with stroke macron accent (a bar over the letter) bar under the letter dot over the letter dot under the letter ring over the letter (for there is also the special command \aa ) breve over the letter caron/hacek ("v") over the letter "tie" (inverted u) over the two letters
\`{o} \'{o} \^{o} \"{o} \H{o} \~{o} \c{c} \k{a} \l \={o} \b{o} \.{o} \d{u} \r{a} \u{o} \v{s} \t{oo}
o u oo
To place a diacritic on top of an i or a j, its dot has to be removed. The dotless version of these letters is accomplished by typing \i and \j . For example: \^\i should be used for i circumflex ''; \"\i should be used for i umlaut ''. If a document is to be written completely in a language that requires particular diacritics several times, then using the right configuration allows those characters to be written directly in the document. For example, to achieve easier coding of umlauts, the babel package can be configured as \usepackage[ngerman]{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.
Special Characters
91
92
Other symbols
LaTeX has lots of symbols at its disposal. The majority of them are within the mathematical domain, and later chapters will cover how to get access to them. For the more common text symbols, use the following commands:
Not mentioned in above table, tilde (~) is used in LaTeX code to produce non-breakable space. To get printed tilde sign, either write \~{} or \textasciitilde{} . And a visible space can be created with \textvisiblespace . For some more interesting symbols, the Postscript ZipfDingbats font is available thanks to the pifont package. Add the declaration to your preamble: \usepackage{pifont} . Next, the command \ding{number} , will print the specified symbol. Here is a table of the available symbols:
Special Characters
93
In special environments
Math mode
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 circumflex wide version of \hat over several letters vee or check tilde wide version of \tilde over several letters acute accent grave accent dot over the letter two dots over the letter (umlaut in text-mode) breve macron vector (arrow) over the letter Description Text-mode equivalence
\hat{o} \widehat{oo} \check{o} \tilde{o} \widetilde{oo} \acute{o} \grave{o} \dot{o} \ddot{o} \breve{o} \bar{o} \vec{o}
\^
\v \~
\' \` \. \" \u \=
When applying accents to letters i and j , you can use \imath and \jmath to keep the dots from interfering with the accents:
Special Characters
94
LaTeX command
Sample
Description circumflex on letter i without upper dot vector (arrow) on letter j without upper dot
\hat{\imath} \vec{\jmath}
Tabbing environment
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
External links
A few other LaTeX accents and symbols [2] NASA GISS: Accents [3]
Internationalization
95
Internationalization
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Internationalization
96 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] LaTeX has to be configured and used appropriately when it is used to write documents in languages other than English. This has to address three main areas: 1. LaTeX needs to know how to hyphenate the language(s) to be used. 2. The user needs to use language-specific typographic rules. In French for example, there is a mandatory space before each colon character (:).
Internationalization 3. The input of special characters, especially for languages using an input system (Arab, Chinese, Japanese, Korean). It is convenient to be able to insert language-specific special characters directly from the keyboard instead of using cumbersome coding (for example, by typing instead of \"{a}). This can be done by configuring input encoding properly. We will not tackle this issue here: see the Special Characters chapter. Some languages require special fonts with the proper font encoding set. See Font encoding. Some of the methods described in this chapter may be useful when dealing with non-English author names in bibliographies. Here is a collection of suggestions about writing a LaTeX document in a language other than English. If you have experience in a language not listed below, please add some notes about it.
97
Prerequisites
Most non-english language will need to input special characters very often. For a convenient writing you will need to set the input encoding and the font encoding properly. The following configuration is optimal for many languages (most latin languages). Make sure your document is saved using the UTF-8 encoding. \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} For more details check Font encoding and Special Characters.
Babel
The babel package by Johannes Braams will take care of everything. You can load it in your preamble, providing as an argument the language you want to use: \usepackage[language]{babel} You should place it soon after the \documentclass command, so that all the other packages you load afterwards will know the language you are using. A list of the languages built into your LaTeX system will be displayed every time the compiler is started. Babel will automatically activate the appropriate hyphenation rules for the language you choose. If your LaTeX format does not support hyphenation in the language of your choice, babel will still work but will disable hyphenation, which has quite a negative effect on the appearance of the typeset document. Babel also specifies new commands for some languages, which simplify the input of special characters. See the sections about languages below for more information. If you call babel with multiple languages: \usepackage[languageA,languageB]{babel} then 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. 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}
Internationalization The starred version of this environment typesets the main text according to the rules of the other language, but keeps the language specific string for ancillary things like figures, in the main language of the document. The environment hyphenrules switches only the hyphenation patterns used; it can also be used to disallow hyphenation by using the language name 'nohyphenation'. The babel manual [1] provides much more information on these and many other options.
98
Multilingual versions
It is possible in LaTeX to typeset the content of one document in several languages and to choose upon compilation which language to output. This might be convenient to keep a consistent sectioning and formatting across the different languages. It is also useful if you make use of multiple proper nouns and other untranslated content.
Preamble
Add this into the preamble. Since you cannot do this easily in LaTeX, we are going to write it in plainTeX. %% Required package. \usepackage{ifthen} %% TeX function that generates the language commands. \def\localedef#1#2{ \ifthenelse{ \equal{\locale}{#1} }{ \selectlanguage{#2} \expandafter\def\csname#1\endcsname ##1{##1} }{ \expandafter\def\csname#1\endcsname ##1{} } } %% Selected language. Can be placed anywhere before the language commands. \providecommand\locale{fr} %% Language commands. \localedef{de}{ngerman} \localedef{en}{english} \localedef{fr}{frenchb} %% ... You can use as many \localedef as you want. You are free to choose the language command names. Keep it short since you are going to use it often. For an explanation on the plainTeX code, see Macros.
Usage
Very simple: enclose the desired content in the appropriate language command. Example: \de{Guten Tag} \en{Good evening} \fr{Bonjour}
Internationalization
99
Specific languages
Arabic script
For languages which use the Arabic script, including Arabic, Persian, Urdu, Pashto, Kurdish, Uyghur, etc., 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[farsi,arabic]{babel} \usepackage[utf8]{inputenc}
You may also copy and paste from PDF files produced with Arabi thanks to the support of the cmap package. You may use Arabi with LyX, or with tex4ht to produce HTML. See Arabi page on CTAN [2]
Cyrillic script
Version 3.7h of babel includes support for the T2* encodings and for typesetting Bulgarian, Russian and Ukrainian texts using Cyrillic letters[3]. Support for Cyrillic is based on standard LaTeX mechanisms plus the fontenc and inputenc packages. AMS-LaTeX packages should be loaded before fontenc and babel. 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[utf8]{inputenc} \usepackage[english,bulgarian,russian,ukranian]{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.
Internationalization 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
100
"| ""--"--~ "--* "" "~ "= ", " " "< ">
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 Bulgarian translation of "The Not So Short Introduction to LaTeX" directly from the keyboard using a different distribution.
[4]
Internationalization
101
Chinese
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)
Czech
Czech is fine using \usepackage[czech]{babel} UTF-8 allows you to have czech quotation marks directly in your text. Otherwise, there are macros \glqq and \grqq to produce left and right quote. You can place quotated text with \uv .
Finnish
Finnish language hyphenation is enabled with: \usepackage[finnish]{babel} This will also automatically change document language (section names, etc.) to Finnish.
French
You can load French language support with the following command: \usepackage[frenchb]{babel} There are multiple options for typesetting French documents, depending on the flavor of French: french, frenchb, and francais for Parisian French, and acadian and canadien for new-world French. If you do not know or do not really care, we would recommend using frenchb . 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:
Internationalization
102
1\ier{}, 1\iere{}, 1\ieres{} 1er, 1re, 1res 2\ieme{} 4\iemes{} \No 1, \no 2 20~\degres C, 45\degres M. \bsc{Durand} \nombre{1234,56789} 2e 4es N 1, n 2 20 C, 45 M. Durand 1 234,567 89
You may want to typeset guillemets and other French characters directly if your keyboard have them. Running Xorg (*BSD and GNU/Linux), you may want to use the oss variant which features some nice shortcuts, like
Key combination Alt Gr + w Alt Gr + x Character
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 rpondit: Ce pain cote-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[frenchb]{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. For more information on what the frenchb option of babel does and how you can customize its behavior, run LaTeX on file frenchb.dtx and read the produced file frenchb.pdf or frenchb.dvi.
Internationalization
103
German
You can load German language support using either one of the two following commands. For old German orthography use \usepackage[german]{babel} or for 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.
"` or \glqq "' or \grqq "< or \flqq "> or \frqq \flq \frq \dq "
In German books you often 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.
Greek
This is the preamble you need to write in the Greek language. Note the particular input encoding. \usepackage[english,greek]{babel} \usepackage[iso-8859-7]{inputenc} This preamble enables hyphenation and changes all automatic text to Greek. A set of new commands also becomes available, which allows you to write Greek input files more easily. In order to temporarily switch to English and vice versa, one can use the commands \textlatin{english text} and \textgreek{greek text} that both take one argument which is then typeset using the requested font encoding. Otherwise you can use the command \selectlanguage{...} described in a previous section. Use \euro for the Euro symbol.
Internationalization
104
Hungarian
Use the following lines: \usepackage[magyar]{babel} More information in hungarian [5]. The Hungarian version of babel included with standard LaTeX distribution is not perfect, a much better version can be downloaded from the previous page.
Italian
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.
Japanese
One possible Japanese support is made available thanks to the CJK package collection. If you are using a package manager or a portage tree, the CJK collection is usually in a separate package because of its size (mainly due to fonts). Make sure your document is saved using the UTF-8 character encoding. See Special Characters for more details. Put the parts where you want to write japanese characters in a CJK environment. \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.
Internationalization
105
Korean
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.
Internationalization \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) [6].
106
Persian script
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} See XePersian page on CTAN [7] Moreover, Arabic script can be used to type Persian as illustrated in the corresponding section.
Polish
If you plan to use Polish in your UTF-8 encoded document, use the following code \usepackage[utf8]{inputenc} \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 Polish has many single letter connectives: "a", "o", "w", "i", 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 bya sierpniowa, ciepa i~sodka, Ksiyc owieca srebrnem wiatem wgbienie, tak, e twarze maego rycerza i~Basi byy skpane w blasku. Poniej, na podwrzu zamkowem, wida byo upione kupy onierzy, a~take i~ciaa zabitych podczas dziennej strzelaniny, bo nie znaleziono dotd czasu na ich pogrzebanie. Numerals 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}.\ara
For articles:
Internationalization 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} Pjd kie t chmurno w gb flaszy. \end{document} Full documentation for those classes is available at http:/ / www. ci. pwr. wroc. pl/ ~pmazur/ LaTeX/ mwclsdoc. pdf (Polish). Indentation It may be customary (depending on publisher) to indent the first paragraph in sections and chapters: \usepackage{indentfirst} Hyphenation and typography 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 According to Polish 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.
107
Internationalization Further information Refer the Sownik Ortograficzny [8] (in Polish) for additional information on Polish grammar and typography rules. Good extract is available at Zasady Typograficzne Skadania Tekstu [9] (in Polish).
108
Portuguese
Add the following code to your preamble: \usepackage[portuguese]{babel} You can substitute the language for brazilian portuguese by choosing brazilian.
Slovak
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[IL2]{fontenc}
Spanish
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 a deviation from standard Babel behavior, and thus may break other programs (LyX, latex2rtf) interacting with LaTeX. Two particularly useful options are es-noquoting,es-nolists: some packages and classes are known to collide with Spanish in the way they handle active characters, and these options disable the internal workings of Spanish to allow you to overcome these common pitfalls. Moreover, these options may simplify the way LyX customizes some features of the Spanish layout from inside the GUI. The options mexico,mexico-com provide support for local custom in Mexico: the former using decimal dot, as customary, and the latter allowing decimal comma, as required by the Mexican Official Norm (NOM) of the Department of Economy for labels in foods and goods. More localizations are in the making. The other commands modify the spanish layout after loading Babel. Two particularly useful commands are \spanishoperators and \spanishdeactivate . The macro \spanishoperators{<list of operators>}{ contains a list of spanish mathematical operators, and may be redefined at will. For instance, the command \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.
Internationalization l\acute{i}m l\acute{i}m\,sup l\acute{i}m\,inf m\acute{a}x m\acute{i}n sen tg arc\,sen arc\,cos arc\,tg cotg cosec senh tgh \acute{i}nf
109
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.
References
[1] http:/ / ftp. snt. utwente. nl/ pub/ software/ tex/ macros/ latex/ required/ babel/ base/ babel. pdf [2] http:/ / www. ctan. org/ tex-archive/ language/ arabic/ arabi/ [3] The Not So Short Introduction to LaTeX (http:/ / www. ctan. org/ tex-archive/ info/ lshort/ english/ lshort. pdf), 2.5.6 Support for Cyrillic, Maksym Polyakov [4] The Not So Short Introduction to LaTeX (http:/ / www. ctan. org/ tex-archive/ info/ lshort/ bulgarian/ lshort-bg. pdf), Bulgarian translation [5] http:/ / www. math. bme. hu/ latex/ [6] http:/ / www. ktug. or. kr/ [7] http:/ / www. ctan. org/ tex-archive/ macros/ xetex/ latex/ xepersian/ [8] http:/ / so. pwn. pl/ zasady. php [9] http:/ / dtp. msstudio. com. pl/ typo. html
Rotations
LaTeX
Rotations
110 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Rotations
111 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
Rotations
112
Options
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
Rotations In two sided documents all sidewaysfigures/sidewaystables are same orientation (left of figure, table now at top of page).
113
Tables
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Tables
114 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] In academic writing, tables are a common feature, often for summarizing results from research. It is therefore a skill that needs mastering in order to produce quality papers. In the end you can print beautiful tables of any kind. Keep in mind that LaTeX is not a spreadsheet, just as it is not a vector graphics tool. So it makes sense to use a dedicated tool to build specific content, then to export it. Basic tables are not too taxing, but you will quickly notice that anything more advanced can take a fair bit of construction. Hopefully some advanced packages will help you out.
Tables It is important to know the basics. Once you are comfortable with basic LaTeX tables, you might have a look at more advanced packages or the export options of your favorite spreadsheet. Thanks to the modular nature of LaTeX, the whole process can be automated in a fairly comfortable way. For a long time the LaTeX tables were quite a chaotic topic, with dozen of packages doing similar things, while not being always compatible one another. Sometimes you had to make trade-offs. The situation changed recently (2010) with the release of the tabu package which combines the power of longtable, tabularx and much more. The tabu environment is far less fragile and restricted than the older alternatives. Nonetheless do not jump to it straightaway; you need to know the classic environment first since tabu works the same way.
115
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 wont 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:
Tables
116
To specify a font format (such as bold, italic, etc.) for an entire column, you can add >{\format} before declare the alignement. 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. 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: & \\ \hline \newline \cline{i-j}
column separator start new row (additional space may be specified after \\ using square brackets, such as \\[6pt]) horizontal line start a new line within a cell (in a paragraph column) partial horizontal line beginning in column i and ending in column j
Note, any white space inserted between these commands is purely down to ones' preferences. I personally add spaces between to make it easier to read.
Basic examples
This example shows how to create a simple table in LaTeX. It is a three-by-three table, but without any lines. \begin{tabular}{ l c r } 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{tabular} Expanding upon that by including some vertical lines: \begin{tabular}{ l | c || r } 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \end{tabular}
To add horizontal lines to the very top and bottom edges of the table: \begin{tabular}{ l | c || r } \hline 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \\ \hline \end{tabular}
And finally, to add lines between all rows, as well as centering (notice the use of the center environment - of course, the result of this is not obvious from the preview on this web page): \begin{center} \begin{tabular}{ l | c || r } \hline 1 & 2 & 3 \\ \hline 4 & 5 & 6 \\ \hline 7 & 8 & 9 \\ \hline \end{tabular} \end{center}
\begin{tabular}{|r|l|} \hline 7C0 & hexadecimal \\ 3700 & octal \\ \cline{2-2} 11111000000 & binary \\ \hline \hline 1984 & decimal \\ \hline \end{tabular}
Tables
117
Tables
118
Note that the first table has been cropped, since the output is wider than the page width.
Tables
119
Tables \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.
120
@-expressions
The column separator can be specified with the @{...} construct. It typically takes some text as its argument, and when appended to a column, it will automatically insert that text into each cell in that column before the actual data for that cell. This command kills the inter-column space and replaces it with whatever is between the curly braces. To add space, use @{\hspace{''width'' }}. Admittedly, this is not that clear, and so will require a few examples to clarify. Sometimes, it is desirable in scientific tables to have the numbers aligned on the decimal point. This can be achieved by doing the following: \begin{tabular}{r@{.}l} 3 & 14159 \\ 16 & 2 \\ 123 & 456 \\ \end{tabular}
Alternatively, to center the column on the decimal separator the dcolumn package may be used, which provides a new column specifier for floating point data. The space-suppressing qualities of the @-expression actually make it quite useful for manipulating the horizontal spacing between columns. Given a basic table, and varying the column descriptions: \begin{tabular}{ |l|l| } \hline stuff & stuff \\ \hline stuff & stuff \\ \hline \end{tabular}
{|@{}l@{}|@{}l@{}|}
Row specification
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
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.
Tables
121
Tables
122
\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}
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} }
Tables
123
Colors
Alternate row colors in tables
The xcolor package provides the necessary commands to produce tables with alternate row colors, when loaded with the table option. The command \rowcolors{<''starting row''>}{<''odd color''>}{<''even color''>} has to be specified right before the tabular environment starts. \documentclass{article} \usepackage[table]{xcolor} \begin{document} \begin{center} \rowcolors{1}{green}{pink} \begin{tabular}{lll} odd & odd & odd \\ even & even & even\\ odd & odd & odd \\ even & even & even\\ \end{tabular} \end{center} \end{document}
The command \hiderowcolors is available to deactivate highlighting 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
Tables
124
Tables
125
\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:
.24">\usepackage{tabularx} % ... \begin{tabularx}{1\textwidth}{ \hsize{1\hsize}\centering}X|>{\setlength\hsize{1\hsize}\raggedleft}X@{} \hsize{1\hsize}\raggedright}X|>{\setlength\hsize{1\hsize}\centering}X| l 1 & \multicolumn{2}{>{\centering\setlength\hsize{2\hsize} }X|}{Label tabularnewline \hline 123 & 123 & 456 & 123 \tabularnewline \hline 123 123 \tabularnewline \hline \end{tabularx}</font> In a way analagous 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.
Tables
126
L left-justified balanced column C centered balanced column R right-justified balanced column J left-right-justified balanced column
or xtab
[4]
, an extended and
Tables
127
Footnotes in tables
The tabular environment does not handle footnotes properly. The longtabular fixes that. Instead of using longtabular we recommand tabu which handles footnotes properly, both in normal and long tables.
Professional tables
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 [5] package is useful for easily providing this professionalism in LaTeX tables, and the documentation [6] 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
\begin{tabular}{llr} \hline \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 \\ \hline \end{tabular}
Tables
128
Using array
\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
\usepackage{booktabs} ... \begin{tabular}{llr} \toprule \multicolumn{2}{c}{Item} \\ \cmidrule(r){1-2} Animal & Description & Price (\$) \\ \midrule Gnat & per gram & 13.65 \\ & each & 0.01 \\ Gnu & stuffed & 92.50 \\ Emu & stuffed & 33.33 \\ Armadillo & frozen & 8.99 \\ \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 [7] 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
Tables can also be put on their side within a document using the rotating or the rotfloat package. See the Rotations chapter.
Tables See the documentation of the eqparbox package for more details.
129
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 show now 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 it's not possible, its placed on the bottom and last possibility is to place it 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.
Tables 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.
130
Using spreadsheets
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 [9]: for OpenOffice.org Calc spreadsheets, excel2latex [10]: for Microsoft Office Excel, matrix2latex [11]: for MATLAB, matrix2latex [12]: for Python and MATLAB, latex-tools [13]: a Ruby library, xtable [14]: a library for R, org-mode [15]: for Emacs users, org-mode tables can be used inline in LaTeX documents, see [16] for a tutorial. Emacs Align Commands [17]: the align commands can clean up a messy LaTeX table. Online Table generator for LATeX [18]: An online tool for creating simple tables within the browser. LaTeX format is directly generated as you type.
However copying the generated source code to your document is not convenient at all. For a maximum a flexibility, generate de source code to a separate file which you can input from you main document file with the \input command. If your speadsheet supports command-line, you can generate your complete document (table included) in one command, using a Makefile for example. See Modular Documents for more details.
Tables
131
References
[1] Package multirow on CTAN (http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ multirow/ ) [2] http:/ / www. ctan. org/ pkg/ tabulary [3] http:/ / www. ctan. org/ pkg/ supertabular [4] http:/ / www. ctan. org/ pkg/ xtab [5] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ booktabs/ [6] http:/ / mirrors. ctan. org/ macros/ latex/ contrib/ booktabs/ booktabs. pdf [7] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ ctable/ [8] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ caption/ [9] http:/ / calc2latex. sourceforge. net/ [10] http:/ / www. ctan. org/ tex-archive/ support/ excel2latex/ [11] http:/ / www. mathworks. com/ matlabcentral/ fileexchange/ 4894-matrix2latex [12] https:/ / code. google. com/ p/ matrix2latex/ [13] http:/ / rubygems. org/ gems/ latex-tools [14] http:/ / cran. r-project. org/ web/ packages/ xtable/ index. html [15] http:/ / orgmode. org/ [16] https:/ / www. gnu. org/ software/ emacs/ manual/ html_node/ org/ A-LaTeX-example. html [17] http:/ / emacswiki. org/ emacs/ AlignCommands [18] http:/ / truben. no/ latex/ table/ [19] http:/ / www. ctan. org/ pkg/ hhline [20] http:/ / www. ctan. org/ pkg/ array [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] http:/ / www. ctan. org/ pkg/ colortbl http:/ / ctan. org/ tex-archive/ macros/ latex/ contrib/ threeparttable http:/ / www. ctan. org/ pkg/ arydshln http:/ / www. ctan. org/ pkg/ ctable http:/ / www. ctan. org/ pkg/ slashbox http:/ / mirror. jmu. edu/ pub/ CTAN/ macros/ latex/ contrib/ diagbox/ http:/ / www. ctan. org/ pkg/ dcolumn http:/ / www. ctan. org/ pkg/ rccol http:/ / www. ctan. org/ pkg/ numprint http:/ / www. ctan. org/ pkg/ spreadtab http:/ / ctan. org/ tex-archive/ macros/ latex/ contrib/ siunitx http:/ / www. ctan. org/ tex-archive/ graphics/ pgf/ contrib/ pgfplots
Title Creation
132
Title Creation
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Title Creation
133 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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. 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.
Title Creation
134
It is meant to be compiled with pdflatex to create a PDF in output. It is a very basic document, but take care that it has the same settings of the document you are writing, so the output won't change when you include the title in
Title Creation your document. In this case (see the first line) the font size is set to 12pt and the paper size is an A4. The package graphicx is included to insert an image in the title. Then a command is defined called \HRule ; it will just insert a horizontal line whose length is like the size of the paper and whose thickness is 0.5 mm. If you want you can change its settings in the definition. Finally the document starts and it simply includes the title.tex file, that must be placed in the same directory of our dummy file test_title.tex. Now create the title.tex and write in it: \begin{titlepage} \end{titlepage} all the things you want to put in the title must be inside the titlepage environment. Now if you compile test_title.tex you will see a preview of your title in the test_title.pdf file. Here is what you need to know to write your title: Alignment if you want to center some text just use \begin{center} ... \end{center} . If you want to align it differently you can use the environment flushright for right-alignment and flushleft for left-alignment. Images the command for including images is the following (the example is for a small logo, but you can introduce any image of any size): \includegraphics[width=0.15\textwidth]{./logo} . There is no \begin{figure} as you usually do because you don't want it to be floating, you just want it there where you placed it. When handling it, remember that it is considered like a big box by the TeX engine. Text size If you want to change the size of some text just place it within brackets, {like this}, and you can use the following commands (in order of size): \Huge , \huge , \LARGE , \Large , \large , \small , \footnotesize , \tiny . So for example: {\large this text is slightly bigger than normal}, this one is not. \normalsize is used to create text at the default size for the document. New lines you can force the start of a new line by \\ . If you want to add more vertical space you don't need to use several new-line commands, just insert some vertical space. For example, this way \\[1cm] you start a new line after having left 1 cm of empty space. Date you can insert the date of the current day with the command \today . If you do not wish to insert any date, keep it blank e.g.\date{} Filling the page the command \vfill keeps on adding empty spaces until the page is full. If you put it in the page, you are sure that all the following text will be placed at the bottom of the page.
135
Title Creation
136
A practical example
All these tips might have made you confused. Then, here is a practical example. Get the test_title.tex described above and here is an example of a title.tex. On the right you can see the output after you compile test_title.tex in PDF: \begin{titlepage} \begin{center} % Upper part of the page. The '~' is needed because \\ % only works if a paragraph has started. \includegraphics[width=0.15\textwidth]{./logo}~\\[1cm] \textsc{\LARGE University of Beer}\\[1.5cm] \textsc{\Large Final year project}\\[0.5cm] % Title \HRule \\[0.4cm] { \huge \bfseries Lager brewing techniques}\\[0.4cm] \HRule \\[1.5cm] % Author and supervisor \begin{minipage}{0.4\textwidth} \begin{flushleft} \large \emph{Author:}\\ John \textsc{Smith} \end{flushleft} \end{minipage} \begin{minipage}{0.4\textwidth} \begin{flushright} \large \emph{Supervisor:} \\ Dr.~Mark \textsc{Brown} \end{flushright} \end{minipage} \vfill % Bottom of the page {\large \today} \end{center} \end{titlepage}
The picture is from a file called logo.png that is in the same directory of both title.tex and test_title.tex. Since I wanted to insert both the author and supervisor names properly aligned I used a trick: I created two small minipages, one on left and one on the right. Their width is a bit less than half of page width (as you can see, they are exactly 40% of the text width). Within the minipages I have used different alignments. Using \vfill I could write the date exactly at the bottom of the page. As you can see, the code looks "dirtier" than standard LaTeX source because you have to take care of the output as well. If you start changing font's output it will get more confused, but you can do it: it's only for the title and your complicated code will be isolated from all the rest within its own file title.tex.
Title Creation
137
Page Layout
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Page Layout
138 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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.
Page Layout
139
Two-sided documents
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
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. 1. one inch + \hoffset 2. one inch + \voffset 3. \oddsidemargin = 31pt 4. 5. 6. 7. 8. \topmargin = 20pt \headheight = 12pt \headsep = 25pt \textheight = 592pt \textwidth = 390pt 1. \marginparsep = 10pt 2. \marginparwidth = 35pt 3. \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{}
Page size
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:
140
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}
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. Thanksfully there is a solution to that: the \special command lets the use 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
Page Layout \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 ... 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.
141
Margins
Readers from a word processing background are probably wondering why there is so much white space surrounding the text. There is a good reason, and it's all down to readability. Have a look in a few books, and pick a few lines at random. Count the number of characters per line. I bet the average is about 66. Studies have shown that it's easier to read text when there are 60-70 characters per line - and it would seem that 66 is the optimal number. Therefore, the page margins are set to ensure that readability remains as good as possible. Also, white space is often left in the inner margin for the assumption that the document will be bound. If you wish to change the margins of your document, there are many ways to do so: Simply use the fullpage package for somewhat standardized smaller margins (around an inch): \usepackage{fullpage} For an even greater effect give it the cm option (around 1.5cm): \usepackage[cm]{fullpage} Use the a4wide package for a page with A4 document size with smaller margins. 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 it. It may be implemented as follows: \usepackage[top=2in, bottom=1.5in, left=1in, right=1in]{geometry} or all in a row \usepackage[margin=1.5in]{geometry} You can combine the margin options with the page size options seen in this paragraph. 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}
Page Layout
142
Page orientation
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.
Page Layout 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}
143
Page styles
Page styles in Latex terms refers not to page dimensions, but to the running headers and footers of a document. These headers typically contain document titles, chapter or section numbers/names, and page numbers.
myheadings Page number is top right, and it is possible to control the rest of the header.
With myheadings, the commands \markright (in the standard document classes, book, report and article) and \markboth (only in the book class) are used to control the headings. The following commands placed at the beginning of an article document will set the header of all pages to contain "John Smith" top left, "On page styles" centered and the page number top right: \pagestyle{myheadings} \markright{John Smith\hfill On page styles\hfill} There are special commands containing details on the running page of the document.
Page Layout
144
number of the current page current chapter name printed like "CHAPTER 3. THIS IS THE CHAPTER TITLE" current section name printed like "1.6. THIS IS THE SECTION TITLE" the name chapter in the current language. If this is English, it will display "Chapter" current chapter number current section number
Note that \leftmark and \rightmark convert the names to uppercase, whichever was the formatting of the text. If you want them to print the actual name of the chapter without converting it to uppercase use the following command: \renewcommand{\chaptermark}[1]{ \markboth{#1}{} \renewcommand{\sectionmark}[1]{ \markright{#1}{} } }
Now \leftmark and \rightmark will just print the name of the chapter and section, without number and without affecting the formatting. Note that these redefinitions must be inserted after the first call of \pagestyle{fancy} . The standard book formatting of the \chaptermark is: \renewcommand{\chaptermark}[1]{\markboth{\MakeUppercase{\chaptername\ \thechapter.\ #1}}{}} Watch out: if you provide long text in two different "parts" only in the footer or only in the header, you might see overlapping text. Moreover, with the following commands you can define the thickness of the decorative lines on both the header and the footer: \renewcommand{\headrulewidth}{0.5pt} \renewcommand{\footrulewidth}{0pt} The first line for the header, the second for the footer. Setting it to zero means that there will be no line. Plain pages issue An issue to look out for is that the major sectioning commands (\part , \chapter or \maketitle ) specify a \thispagestyle{plain} . So, if you wish to suppress all styles by inserting a \pagestyle{empty} at the beginning of your document, then the style command at each section will override your initial rule, for those pages only. To achieve the intended result one can follow the new section commands with \thispagestyle{empty} . The \part command, however, cannot be fixed this way, because it sets the page style, but also advances to the next page, so that \thispagestyle{} cannot be applied to that page. Two solutions: simply write \usepackage{nopageno} in the preamble. This package will make \pagestyle{plain} have the same effect as \pagestyle{empty} , effectively suppressing page numbering when it is used. Use fancyhdr as described below. The tricky problem when customizing headers and footers is to get things like running section and chapter names in there. Standard LaTeX accomplishes this with a two-stage approach. In the header and footer definition, you use the commands \rightmark and \leftmark to represent the current section and chapter heading, respectively. The values of these two commands are overwritten whenever a chapter or section command is processed. For ultimate flexibility, the \chapter command and its friends do not redefine \rightmark and \leftmark themselves. They call yet another command (\chaptermark , \sectionmark , or \subsectionmark ) that is responsible for redefining \rightmark and \leftmark , except if they are starred -- in such a case,
Page Layout \markboth{Chapter/Section name}{} must be used inside the sectioning command if header and footer lines are to be updated. Again, several packages provide a solution: an alternative one-stage mechanism is provided by the package titleps); fancyhdr will handle the process its own way.
145
Page Layout
146
so CE,RO will refer to the center of the even pages and to the right side of the odd pages. \fancyhf is a merge of \fancyhead and \fancyfoot , hence the name. There is two additional selectors H and F to specify the header or the footer respectively. If you omit the H or the F, it will set the fields for both. These commands will only work for fancy and fancyplain. To customize LaTeX default style you need the \fancyplainstyle command. See below for examples. For a clean customization, we recommend you start from scratch. To do so you should erase the current pagestyle. Providing empty values will make the field blank. So \fancyhf{} will just delete the current heading/footer configuration, so you can make your own. Plain pages There is two ways to change the style of plain pages like chapters and titlepage. First you can use the fancyplain style. If you do so, you can use the command \fancyplain{...}{...} inside fancyhdr commands like \lhead{...} , etc. When LaTeX wants to create a page with an empty style, it will insert the first argument of \fancyplain , in all the other cases it will use the second argument. For instance: \pagestyle{fancyplain} \fancyhf{} \lhead{ \fancyplain{}{Author Name} } \rhead{ \fancyplain{}{\today} } \rfoot{ \fancyplain{}{\thepage} } It has the same behavior of the previous code, but you will get empty header and footer in the title and at the beginning of chapters. Alternatively you could redefine the plain style, for example to have a really plain page when you want. The command to use is \fancypagestyle{plain}{...} and the argument can contain all the commands explained before. An example is the following: \pagestyle{fancy} \fancypagestyle{plain}{ \renewcommand{\headrulewidth}{0pt} % \renewcommand{\footrulewidth}{0pt} } % \fancyhf{} % remove everything remove lines as well
In that case you can use any style but fancyplain because it would override your redefinition.
Page Layout Examples For two-sided, it's common to mirror the style of opposite pages, you tend to think in terms of inner and outer. So, the same example as above for two-sided is: \lhead[Author Name]{} \rhead[]{Author Name} \lhead[]{\today} \rhead[\today]{} \lfoot[\thepage]{} \rfoot[]{\thepage} This is effectively saying author name is top outer, today's date is top inner, and current page number is bottom outer. Using \fancyhf can make it shorter: \fancyhf[HLE,HRO]{Author's \fancyhf[FLE,FRO]{\thepage} Name} \fancyhf[HRE,HLO]{\today}
147
Here is the complete code of a possible style you could use for a two-sided document: \usepackage{fancyhdr} \setlength{\headheight}{15pt} \pagestyle{fancy} \renewcommand{\chaptermark}[1]{ \markboth{#1}{} } \renewcommand{\sectionmark}[1]{ \markright{#1}{} } \fancyhf{} \fancyhead[LE,RO]{\thepage} \fancyhead[RE]{\textit{ \nouppercase{\leftmark}} } \fancyhead[LO]{\textit{ \nouppercase{\rightmark}} } \fancypagestyle{plain}{ % \fancyhf{} % remove everything \renewcommand{\headrulewidth}{0pt} % remove lines as well \renewcommand{\footrulewidth}{0pt} } Using \fancypagestyle one can additionally define multiple styles for one's document that are easy to switch between. Here's a somewhat complicated example for a two-sided book style: \fancypagestyle{fancybook}{% \fancyhf{}% % Note the ## here. It's required because \fancypagestyle is making a macro (\ps@fancybook). % If we just wrote #1, TeX would think that it's the argument to \ps@fancybook, but % \ps@fancybook doesn't take any arguments, so TeX would complain with an error message. % You are not expected to understand this. \renewcommand*{\sectionmark}[1]{ \markright{\thesection\ ##1} }% \renewcommand*{\chaptermark}[1]{ \markboth{\chaptername\ \thechapter: ##1}{} }% % Increase the length of the header such that the folios % (typography jargon for page numbers) move into the margin \fancyhfoffset[LE]{6mm}% slightly less than 0.25in \fancyhfoffset[RO]{6mm}% % Put some space and a vertical par between the folio and the rest of the header \fancyhead[LE]{\thepage\hskip3mm\vrule\hskip3mm\leftmark}% \fancyhead[RO]{\rightmark\hskip3mm\vrule\hskip3mm\thepage}% }
Page n of m
Some people like to put the current page number in context with the whole document. LaTeX only provides access to the current page number. However, you can use the lastpage package to find the total number of pages, like this: \usepackage{lastpage} ... \cfoot{\thepage\ of \pageref{LastPage} } Note the capital letters. Also, add a backslash after \thepage to ensure adequate space between the page number and 'of'. And recall, when using references, that you have to run LaTeX an extra time to resolve the cross-references.
Page Layout
148
Alternative packages
Other packages for page styles are scrpage2, very similar to fancyhdr, and titleps, which takes a one-stage approach, without having to use \leftmark or \rightmark .
Page background
The eso-pic package will let you print content in the package 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.
Multi-column pages
It is common to see articles and conference proceedings formatted with two columns of text. However, such publishers will usually provide you with their own document class, which automatically implements this format, without you having to do anything. It is very easy to format your page in this way. If you are using a standard Latex document class, then you can simply pass the optional argument twocolumn to the document class: \documentclass[twocolumn]{article} which will give the desired effect. While this simple addition will do the job 9 out of 10 times, it is widely acknowledged that there are many limitations of this approach, and that the multicol package is much more useful for handling multiple columns. It has several advantages: Can support up to ten columns. Implements a multicols environment, therefore, it is possible to mix the number of columns within a document. Additionally, the environment can be nested inside other environments, such as figure. multicol outputs balanced columns, whereby the columns on the final page will be of roughly equal length. Vertical rules between columns can be customised. Column environments can be easily customised locally or globally.
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. To create a typical two-column layout: \begin{multicols}{2} lots of text \end{multicols} The parameter \columnseprule holds the width of the vertical rules. By default, the lines are omitted as this parameter is set to a length of 0pt. Do the following before the beginning of the environment: \setlength{\columnseprule}{1pt} This will draw a thin line of 1pt in width. A thick line would not look very pleasing, however, you are free to put in any length of your choosing. Also, to change the horizontal space in between columns (the default is set at 10pt, which is quite narrow) then you need to change the \columnsep parameter:
Page Layout \setlength{\columnsep}{20pt} To force a break in a column, the command \columnbreak is used in a multicols environment.
149
References
[1] http:/ / www. ctex. org/ documents/ packages/ layout/ titlesec. pdf [2] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ fancyhdr/ fancyhdr. pdf
Importing Graphics
150
Importing Graphics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Importing Graphics
151 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] There are two possibilities to include graphics in your document. Either create them with some special code, a topic which will be discussed in the Creating Graphics part, (see Introducing Procedural Graphics) or import productions from third party tools, which is what we will be discussing here. Strictly speaking, LaTeX cannot manage pictures directly: in order to introduce graphics within documents, LaTeX just creates a box with the same size as the image you want to include and embeds the picture, without any other processing. This means you will have to take care that the images you want to include are in the right format to be
Importing Graphics included. This is not such a hard task because LaTeX supports the most common picture formats around.
152
Document Options
The graphics and graphicx packages recognize the draft and final options given in the \documentclass[...]{...} command at the start of the file. (See Document Classes.) Using draft as the option will suppress the inclusion of the image in the output file and will replace the contents with the name of the image file that would have been seen. Using final will result in the image being placed in the output file. The default is final.
Importing Graphics case, you can still use both compilers with documents with pictures as well, as long as you always remember to provide the pictures in two formats (EPS and one of JPG, PNG or PDF).
153
Including graphics
Now that we have seen which formats we can include and how we could manage those formats, it's time to learn how to include them in our document. After you have loaded the graphicx package in your preamble, you can include images with \includegraphics , whose syntax is the following: \includegraphics[attr1=val1, attr2=val2, ..., attrn=valn]{imagename} As you should hopefully be aware by now, arguments in square brackets are optional, whereas arguments in curly braces are compulsory. The argument in the curly braces is the name of the image. Write it without the extension. This way the LaTeX compiler will look for any supported image format in that directory and will take the best one (EPS if the output is DVI; JPEG, PNG or PDF if the output is PDF). Images can be saved in multiple formats for different purposes. For example, a directory can have "diagram.pdf" for high-resolution printing, while "diagram.png" can be used for previewing on the monitor. You can specify which image file is to be used by pdflatex through the preamble command: \DeclareGraphicsExtensions{.pdf,.png,.jpg} which specifies the files to include in the document, if files with the same basename exist, but with different extensions. The variety of possible attributes that can be set is fairly large, so only the most common are covered below:
Importing Graphics
154
width=xx height=xx
Specify the preferred width of the imported image to xx. Specify the preferred height of the imported image to xx.
NB. Only specifying either width or height will scale the image whilst maintaining the aspect ratio.
keepaspectratio This can be set to either true or false. When true, it will scale the image according to both height and width, but will not distort the image, so that neither width nor height are exceeded. scale=xx angle=xx trim=l b r t Scales the image by the desired scale factor. e.g, 0.5 to reduce by half, or 2 to double. This option can rotate the image by xx degrees (counter-clockwise) This option will crop the imported image by l from the left, b from the bottom, r from the right, and t from the top. Where l, b, r and t are lengths. For the trim option to work, you must set clip=true. If the image file is a pdf file with multiple pages, this parameter allows you to use a different page than the first.
clip page=x
In order to use more than one option at a time, simply separate each with a comma. The order you give the options matters. E.g you should first rotate your graphic (with angle) and then specify its width. Included graphics will be inserted just there, where you placed the code, and the compiler will handle them as "big boxes". As we will see in the floats section, this can disrupt the layout; you'll probably want to place graphics inside floating objects. Also note that the trim option does not work with XeLaTex. Be careful using any options, if you are working with the chemnum-package. The labels defined by \cmpdref{<label name>} might not behave as expected. Scaling the image for instance may be done by \scalebox instead. The star version of the command will work for .eps files only. For a more portable solution, the standard way should take precedence. The star command will take the crop dimension as extra parameter: \includegraphics*[100,100][300,300]{mypicture}
Examples
OK, it's time to see graphicx in action. Here are some examples: \includegraphics{chick} This simply imports the image, without any other processing. However, it is very large (so I won't display it here!). So, let's scale it down: \includegraphics[scale=0.5]{chick}
This has now reduced it by half. If you wish to be more specific and give actual lengths of the image dimensions, this is how to go about it: \includegraphics[width=2.5cm]{chick}
Importing Graphics
155
One can also specify the scale with respect to the width of a line in the local environment (\linewidth ), the width of the text on a page (\textwidth ) or the height of the text on a page (\textheight ) (pictures not shown): \includegraphics[width=\linewidth]{chick} \includegraphics[width=\textwidth]{chick} \includegraphics[height=\textheight]{chick} To rotate (I also scaled the image down): \includegraphics[scale=0.5, angle=180]{chick}
And finally, an example of how to crop an image should you wish to focus on one particular area of interest: %trim option's parameter order: left bottom right top \includegraphics[trim = 10mm 80mm 20mm 5mm, clip, width=3cm]{chick} Note the presence of clip, as the trim operation will not work without it. Trick: You can also use negative trim values to add blank space to your graphics, in cases where you need some manual alignment.
Spaces in names
If the image above was called (say) "chick picture" instead of just "chick", then the space in the name would cause the title to be imported with the image like this: \includegraphics[scale=0.5]{chick picture.png}
chick picture.png
or similar. The solution is to not use spaces in names (if possible), or to simply replace spaces with underscores. So the name "chick picture" should be exactly as above (as "chick", since "picture" is obvious redundancy), or as "chick_picture". The text should not appear.
Importing Graphics
156
\includegraphics[scale=0.5]{chick_picture.png}
Borders
It is possible to have LaTeX create a border around your image by using \fbox : \setlength\fboxsep{0pt} \fbox{\includegraphics{chick}} \setlength\fboxrule{0.5pt}
You can control the border padding with the \setlength\fboxsep{0pt} command, in this case I set it to 0pt to avoid any padding, so the border will be placed tightly around the image. You can control the thickness of the border by adjusting the \setlength\fboxrule{0.5pt} command. See Boxes for more details on \framebox and \fbox .
Graphics storage
The command \graphicspath tells LaTeX where to look for images, which can be useful if you store images centrally for use in many different documents. The \graphicspath command takes one argument, which specifies the additional paths you want to be searched when the \includegraphics command is used. Here are some examples (trailing / is required): \graphicspath{ {/var/lib/images/} } \graphicspath{ {images_folder/}{other_folder/}{third_folder/} } \graphicspath{ {./images/} } \graphicspath{ {c:\mypict~1\camera} } \graphicspath{ {c:/mypict~1/camera/} } % works well in Win XP Please see http:/ / www. ctan. org/ tex-archive/ macros/ latex/ required/ graphics/ grfguide. pdf. In the third example shown there should be a directory named "images" in the same directory as your main tex file, i.e. this is RELATIVE addressing. Using absolute paths, \graphicspath makes your file less portable, while using relative paths (like the third example), there should not be any problem with portability. The forth example uses the "safe" (MS-DOS) form of the Windows MyPictures folder because it's a bad idea to use directory names containing spaces. Again, ensure file names do not contain spaces or alternatively if you are using PDFLaTeX, you can use the package grffile which will allow you to use spaces in file names. Note that you cannot make the graphicx package search directories recursively. Under Linux/Unix, you can achieve a recursive search using the environment variable TEXINPUTS, e.g., by setting it to export TEXINPUTS=./images//:./Snapshots// before running latex/pdflatex or your TeX-IDE. (But this, of course, is not a portable method.)
Importing Graphics
157
Images as figures
The figure environment is not exclusively used for images. We will only give a short preview of figures here. More information on the figure environment and how to use it can be found in Floats, Figures and Captions. There are many scenarios where you might want to accompany an image with a caption and possibly a cross-reference. This is done using the figure environment. The following code sample shows the bare minimum required to use an image as a figure. \begin{figure}[p] \includegraphics{image.png} \end{figure} The above code extract is relatively trivial, and doesn't offer much functionality. The following code sample shows an extended use of the figure environment which is almost universally useful, offering a caption and label, centering the image and scaling it to 80% of the width of the text. \begin{figure}[p] \centering \includegraphics[width=0.8\textwidth]{image.png} \caption{Awesome Image} \label{fig:awesome_image} \end{figure}
Importing Graphics
158
addtolist
Like addtotoc, addtolist accepts multiple sets of the above mentioned four arguments, all separated by commas. The proper recursive definition is: addtolist={ page number , type , heading , label [,
lof-list ] }
pagecommand Declares LaTeX-commands, which are executed on each sheet of paper. (Default: pagecommand={\thispagestyle{empty}}pagecommand={\label{fig:mylabel}}
You can also inserts pages of several external PDF documents. \includepdfmerge[ key=val ]{ file-page-list } Several PDFs can be placed table-like on one page. See more information in its documentation [3].
Importing Graphics
159
Converting graphics
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 [4], included in package of the same name. This tool is actually called by pdflatex to convert EPS files to PDF in the background when the graphicx package is loaded. This process is completely invisible to the user. You can batch convert files using the command-line. In Bourne Shell (Unix) this can be done by: $ for i in *.eps; do epstopdf "$i"; done In Windows, multiple files can be converted by placing the following line in a batch file (a text file with a .bat extension) in the same directory as the images: for %%f in (*.eps) do epstopdf %%f which can then be run from the command line. If epstopdf produces whole page with your small graphics somewhere on it, use $ epstopdf --gsopt=-dEPSCrop foo.eps or try using ps2pdf utility which should be installed with Ghostscript (required for any TeX distribution). $ ps2pdf -dEPSCrop foo.eps to crop final PDF. eps2eps When all of the above fails, one can simplify the EPS file before attempting other conversions, by using the eps2eps [5] 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 [6] 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. 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 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).
[7]
Importing Graphics PDFCreator Under Windows, PDFCreator [8] 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 [9] (convert) or ImageMagick [10] (convert) or GraphicsMagick [11] (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.
160
Importing Graphics
161
Vector graphics
Dia Dia [14] 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 [15]. It can run natively under Windows, Linux or Mac OS X (with X11).It works with Scalable Vector Graphics (SVG) [16] 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 [17] 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. An extremely useful plug-in is textext [18], 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 [19], which allows TeX annotations to imported graphics. See Labels in the figures. OpenOffice.org It is also possible to export vector graphics to EPS format using OpenOffice.org Draw, which is an open source office suite available for Windows, Linux and Mac. TpX Vector editor TpX [20] 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 [21]; 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 [22] is an attempt to achieve the functionality of xfig on Windows computers. There are many ways to use xfig to create graphics for LaTeX documents. One method is to export the drawing as a LaTeX document. This method, however, suffers from various drawbacks: lines can be drawn only at angles that are multiples of 30 and 45 degrees, lines with arrows can only be drawn at angles that are multiples of 45 degrees, several curves are not supported, etc. Exporting a file as PDF/LaTeX or PS/LaTeX, on the other hand, offers a good deal more flexibility in drawing. Here's how it's done: 1. Create the drawing in xfig. Wherever you need LaTeX text, such as a mathematical formula, enter a LaTeX string in a textbox.
Importing Graphics 2. Use the Edit tool to open the properties of each of those textboxes, and change the option on the "Special Flag" field to Special. This tells LaTeX to interpret these textboxes when it opens the figure. 3. Go to File -> Export and export the file as PDF/LaTeX (both parts) or PS/LaTeX (both parts), depending on whether you are using pdflatex or pslatex to compile your file. 4. In your LaTeX document, where the picture should be, use the following, where "test" is replaced by the name of the image: \begin{figure}[htbp] \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. 5. 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 [23] of the xfig User Manual [24] 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.
162
Raster graphics
Adobe Photoshop It can save to EPS. GIMP GIMP [25], has a graphical user interface, and it is multi-platform. It can save to EPS and PDF.
Importing Graphics
163
164
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
165 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] The previous chapter introduced importing graphics. However, just having a picture stuck in between paragraphs does not look professional. For starters, we want a way of adding captions, and to be able to cross-reference. What we need is a way of defining figures. It would also be good if LaTeX could apply principles similar to when it arranges text to look its best to arranging pictures as well. This is where floats come into play.
166
Floats
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.
Figures
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 h t b p ! H Permission Place the float here, i.e., approximately at the same point it occurs in the source text (however, not exactly at the spot) Position at the top of the page. Position at the bottom of the page. Put on a special page for floats only. Override internal parameters LaTeX uses for determining "good" float positions. Places the float at precisely the location in the LaTeX code. Requires the float package, is somewhat equivalent to h!. [1] e.g., \usepackage{float} . This
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. 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[2]. 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.
Floats, Figures and Captions Figures with borders 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.
167
Tables
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} \end{table} \begin{tabular}{...} ... table data ... \end{tabular}
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.
Captions
It is always good practice to add a caption to any figure or table. Fortunately, this is very simple in LaTeX. All you need to do is use the \caption{''text''} command within the float environment. Because of how LaTeX deals sensibly with logical structure, it 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:
168
\documentclass[a4paper,12pt]{article} \usepackage[english]{babel} \usepackage{graphicx} \begin{document} \begin{figure}[h!] \caption{A picture of a gull.} \centering \includegraphics[width=0.5\textwidth]{gull} \end{figure} \begin{figure}[h!] \centering \reflectbox{% \includegraphics[width=0.5\textwidth]{gull}} \caption{A picture of the same gull looking the other way!} \end{figure} \begin{table}[h!] \begin{center} \begin{tabular}{
Side captions
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. \documentclass{article} \usepackage[pdftex]{graphicx} \usepackage{sidecap} \begin{document} \begin{SCfigure} \centering \includegraphics[width=0.5\textwidth]% {Giraff_picture}% picture filename \caption{ ... caption text ... } \end{SCfigure} \end{document}
Unnumbered captions
In some types of document (such as presentations), it may not be desirable for figure captions to start Figure:. This is easy to suppress by just placing the caption text in the Figure environment, without enclosing it in a Caption. This however means that there is no caption available for inclusion in a list of figures.
169
\documentclass[12pt]{article} \usepackage{graphicx} \begin{document} \listoffigures \section{Introduction} \begin{figure}[hb] \centering \includegraphics[width=4in]{gecko} \caption[Close up of \textit{Hemidactylus} sp.] {Close up of \textit{Hemidactylus} sp., which is part the genus of the gecko family. It is the second most speciose genus in the family.} \end{figure} \end{document}
The uppercase-character allows the figure to float, while the lowercase version means "exactly here". [5] The width is, of course, the width of the figure. An example:
170
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.
171
\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 [6]. (For documentation see [7].) To remove the white space from a figure once for all, one should refer to the program pdfcrop, included in most TeX installations.
Subfloats
A useful extension is the subcaption package [8] (the subfigure and subfig packages are deprecated and shouldn't be used any more), which uses subfloats within a single float. This gives 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 this package: \usepackage{graphicx} \usepackage{caption} \usepackage{subcaption} \begin{figure} \centering \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{gull} \caption{A gull} \label{fig:gull} \end{subfigure}% ~ %add desired spacing between images, e. g. ~, \quad, \qquad etc. %(or a blank line to force the subfigure onto a new line) \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{tiger} \caption{A tiger} \label{fig:tiger} \end{subfigure} ~ %add desired spacing between images, e. g. ~, \quad, \qquad etc. %(or a blank line to force the subfigure onto a new line) \begin{subfigure}[b]{0.3\textwidth} \centering \includegraphics[width=\textwidth]{mouse} \caption{A mouse} \label{fig:mouse} \end{subfigure} \caption{Pictures of animals}\label{fig:animals} \end{figure}
172
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
Floats, Figures and Captions To prevent the figures from being placed out-of-order with respect to their "non-starred" counterparts, the package fixltx2e [9] should be used (e.g. \usepackage{fixltx2e} ).
173
Custom Floats
If tables and figures are not adequate for your needs, then you always have the option to create your own! Examples of such instances could be source code examples, or maps. For a program float example, one might therefore wish to create a float named program. The package float is your friend for this task. All commands to set up the new float must be placed in the preamble, and not within the document. 1. Add \usepackage{float} to the preamble of your document 2. Declare your new float using: \newfloat{type}{placement}{ext}[outer counter] , where: type - the new name you wish to call your float, in this instance, 'program'. placement - t, b, p, or h (as previously described in Placement), where letters enumerate permitted placements. ext - the file name extension of an auxiliary file for the list of figures (or whatever). Latex writes the captions to this file. outer counter - the presence of this parameter indicates that the counter associated with this new float should depend on outer counter, for example 'chapter'. 3. The default name that appears at the start of the caption is the type. If you wish to alter this, use \floatname{type}{floatname} 4. Changing float style can be issued with \floatstyle{style} (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 environment is an environment that is already part of Latex. Although not introduced so far, its name is fairly intuitive! LaTeX will reproduce everything you give it, including new lines, spaces, etc. It is good for source code, but if you want to introduce a lot of code you might consider using the listings package, 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
Floats, Figures and Captions with caption, numbering, an index file with the extension .lob and a customization of the float's visual layout:
174
\documentclass{article} % have hyperref package before float in order to get strange errors with .\theHfloatbox \usepackage[pdftex]{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
To change the appearance of captions, use the caption [10] package. For example, to make all caption labels small and bold: \usepackage[font=small,labelfont=bf]{caption} The KOMA script packages [11] 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.
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.
175
Summary
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.
This page uses material from Andy Roberts' Getting to grips with LaTeX (http:/ / www. andy-roberts. net/ writing/ latex) with permission from the author.
Hyperlinks
LaTeX
Hyperlinks
176 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Hyperlinks
177 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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.
Hyperlinks
178
Hyperref
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, and the only way to introduce them in LaTeX is using hyperref. 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
The basic usage with the standard settings is straightforward. Just load the package in the preamble, at the end of all the other packages but prior to other settings: \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
The package provides some useful commands for inserting links pointing outside the document. \hyperref 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} }. with the hyperlink as expected. Note the "*" after \ref for avoiding nested hyperlinks. \url 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 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:
We use lemma 4.1.1.
Hyperlinks \url{http://www.wikibooks.org} \href{http://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.
179
Other possibilities
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 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 preceeded by a \protect command. Local file 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} 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.) Hyperlink and Hypertarget 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.
Hyperlinks
180
Customization
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 [3]
variable bookmarks unicode pdfborder values =true,false =false,true ={RadiusH RadiusV Width [Dash-Pattern]} comment show or hide the bookmarks bar when displaying the document allows to use characters of non-Latin based languages in Acrobats bookmarks 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. show or hide Acrobats toolbar show or hide Acrobats menu resize document window to fit document size fit the width of the page to the window define the title that gets displayed in the "Document Info" window of Acrobat the name of the PDFs author, it works like the one above subject of the document, it works like the one above creator of the document, it works like the one above producer of the document, it works like the one above list of keywords, separated by brackets, example below define if a new window should get opened when a link leads out of the current document activate back references inside bibliography. Must be specified as part of the \usepackage{} statement. 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): hide links (removing color and border)
pdftoolbar pdfmenubar pdffitwindow pdfstartview pdftitle pdfauthor pdfsubject pdfcreator pdfproducer pdfkeywords pdfnewwindow
=true,false =true,false =true,false [4] ={FitH},{FitV},etc . ={text} ={text} ={text} ={text} ={text} ={text} (=true,false)
pagebackref
(=false,true)
colorlinks
(=false,true)
hidelinks
Hyperlinks
181
=red =none,section,page,all =green =magenta =cyan color of internal links (sections, pages, etc.) defines which part of an entry in the table of contents is made into a link color of citation links (bibliography) color of file links color of URL links (mail, web) color of frame around internal links (if colorlinks=false) color of frame around citations 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 Acrobats bookmarks pdftoolbar=true, % show Acrobats toolbar? pdfmenubar=true, % show Acrobats 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 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=magenta, % color of file links urlcolor=cyan % 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} 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},% pagebackref=true,% pdftex]{hyperref} pdftitle={Document Title},%
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}
Hyperlinks
182
Troubleshooting
Problems with Links and Equations
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 made 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.
Hyperlinks 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.
183
Hyperlinks
184
185
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
186 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
187
Introduction
Another good point of LaTeX is that you can easily reference almost anything that is numbered (sections, figures, formulas), and LaTeX will take care of numbering, updating it whenever necessary. The commands to be used do not depend on what you are referencing, and they are: \label{marker} you give the object you want to reference a marker, you can see it like a name. \ref{marker} you can reference the object you have marked before. This prints the number that was assigned to the object. \pageref{marker} It will print the number of the page where the object is. LaTeX will calculate the right numbering for the objects in the document; the marker you have used to label the object will not be shown anywhere in the document. Then LaTeX will replace the string "\ref{marker}" with the right number that was assigned to the object. If you reference a marker that does not exist, the compilation of the document will be successful but LaTeX will return a warning: LaTeX Warning: There were undefined references. and it will replace "\ref{unknown-marker}" with "??" (so it will be easy to find in the document). As you may have noticed reading how it works, it is a two-step process: first the compiler has to store the labels with the right number to be used for referencing, then it has to replace the \ref with the right number. That is why, when you use references, you have to compile your document twice to see the proper output. If you compile it only once, LaTeX will use the older information it collected in previous compilations (that might be outdated), but the compiler will inform you printing on the screen at the end of the compilation: LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right. Using the command \pageref{} you can help the reader to find the referenced object by providing also the page number where it can be found. You could write something like: See figure~\ref{fig:test} on page~\pageref{fig:test}. Since you can use exactly the same commands to reference almost anything, you might get a bit confused after you have introduced a lot of references. It is common practice among LaTeX users to add a few letters to the label to describe what you are referencing. Some packages, such as fancyref, rely on this meta information. Here is an example:
chap: chapter sec: fig: tab: eq: lst: itm: section figure table equation code listing enumerated list item
Following this convention, the label of a figure will look like \label{fig:my_figure}, etc. You are not obligated to use these prefixes. You can use any string as argument of \label{...}, but these prefixes become increasingly useful as your document grows in size.
Labels and Cross-referencing Another suggestion: try to avoid using numbers within labels. You are better off describing what the object is about. This way, if you change the order of the objects, you will not have to rename all your labels and their references. If you want to be able to see the markers you are using in the output document as well, you can use the showkeys package; this can be very useful while developing your document. For more information see the Packages section.
188
Examples
Here are some practical examples, but you will notice that they are all the same because they all use the same commands.
Sections
\section{Greetings} \label{sec:greetings} Hello! \section{Referencing} I greeted in section~\ref{sec:greetings}.
You could place the label anywhere in the section; 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. The tilde (~) indicates a non-breaking space.
Pictures
You can reference a picture by inserting it in the figure floating environment. \begin{figure} \centering \includegraphics[width=0.5\textwidth]{gull} \caption{Close-up of a gull} \label{gull} \end{figure} Figure~\ref{gull} shows a photograph of a gull.
189
When a label is declared within a float environment, the \ref{...} will return the respective fig/table number, but it must occur after the caption. When declared outside, it will give the section number. To be completely safe, the label for any picture or table can go within the \caption{} command, as in \caption{Close-up of a gull\label{gull}} See the Floats, Figures and Captions section for more about the figure and related environments. Fixing wrong labels The command \label must appear after (or inside) \caption. Otherwise, it will pick up the current section or list number instead of what you intended. \begin{figure} \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 In case you use the package hyperref to create a PDF, the links to tables or figures will point to the caption of the table or figure, which is always below the table or figure itself[1]. Therefore the table or figure will not be visible, if it is above the pointer and one has to scroll up in order to see it. If you want the link point to the top of the image you can give the option hypcap to the caption package: \usepackage[hypcap]{caption}
Formulae
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
Labels and Cross-referencing \end{equation} \begin{equation} x_2 = \frac{5 - \sqrt{25 - 4 \times 6}}{2} = 2 \end{equation} and so we have solved equation ~\ref{eq:solve}
190
As you can see, the label is placed soon after the beginning of the math mode. In order to reference a formula, you have to use an environment that adds numbers. Most of the times you will be using the equation environment; that is the best choice for one-line formulae, whether you are using amsmath or not. Note also the eq: prefix in the label. eqref The amsmath package adds a new command for referencing formulae; it is \eqref{}. It works exactly like \ref{}, but it adds brackets so that, instead of printing a plain number as 5, it will print (5). This can be useful to help the reader distinguish between formulae and other things, without the need to repeat the word "formula" before any reference. Its output can be changed as desired; for more information see the amsmath documentation. tag The \tag{eqnno} command is used to manually set equation numbers where eqnno is the arbitrary text string you want to appear in the document. It is normally better to use labels, but sometimes hard-coded equation numbers might offer a useful work-around. numberwithin The amsmath package adds the \numberwithin{countera}{counterb} command which replaces the simple countera by a more sophisticated counterb.countera. For example \numberwithin{equation}{section} in the preamble will prepend the section number to all equation numbers. cases 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.
191
192
nameref
The hyperref package also automatically includes the nameref package, and a similarly named command. It is similar to \autoref{}, but inserts text corresponding to the section name, for example. Input: \section{MyFirstSection} \label{sec:marker} \section{MySecondSection} In section~\nameref{sec:marker} we defined... Output: In section MyFirstSection we defined...
193
Mechanics
Errors and Warnings
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
194 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] LaTeX describes what it's typesetting while it does it, and if it encounters something it doesn't understand or can't do, it will display a message saying what's wrong. It may also display warnings for less serious conditions. Don't panic if you see error messages: it's very common to mistype or 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 next sections.
195
Error messages
The format of an error message is always the same. Error messages begin with an exclamation mark at the start of the line, and give a description of the error, followed by another line starting with the number, which refers to the line-number in your document file which LaTeX was processing when the error was spotted. Here's an example, showing that the user mistyped the \tableofcontents command: ! Undefined control sequence. l.6 \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 x q e Stop immediately and exit the program. Carry on quietly as best you can and don't bother me with any more error messages. 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). Try to give me more help. (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). run in non-stop mode. Plow through any errors, unless too many pile up and it fails (100 errors). Meaning
h i
Some systems (Emacs is one example) run LaTeX with a "nonstop" switch turned on, so it will always process through to the end of the file, regardless of errors, or until a limit is reached.
Warnings
Warnings don't begin with an exclamation mark: they are just comments by LaTeX about things you might want to look into, such as overlong or underrun lines (often caused by unusual hyphenations, for example), pages running short or long, and other typographical niceties (most of which you can ignore until later). Unlike other systems, which try to hide unevennesses in the text (usually unsuccessfully) by interfering with the 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
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.
196
Runaway argument
Runaway argument? {December 2004 \maketitle ! Paragraph ended before \date was complete. <to be read again> \par l.8 In this error, the closing curly brace has been omitted from the date. It's the opposite of the error of too many }'s, and it results in \maketitle trying to format the title page while LaTeX is still expecting more text for the date! As \maketitle creates new paragraphs on the title page, this is detected and LaTeX complains that the previous paragraph has ended but \date is not yet finished.
197
Underfull hbox
Underfull \hbox (badness 1394) in paragraph at lines 28--30 [][]\LY1/brm/b/n/10 Bull, RJ: \LY1/brm/m/n/10 Ac-count-ing in Busi[94] This is a warning that LaTeX cannot stretch the line wide enough to fit, without making the spacing bigger than its currently permitted maximum. The badness (0-10,000) indicates how severe this is (here you can probably ignore a badness of 1394). It says what lines of your file it was typesetting when it found this, and the number in square brackets is the number of the page onto which the offending line was printed. The codes separated by slashes are the typeface and font style and size used in the line. Ignore them for the moment. This comes up if you force a linebreak, e.g., \\, and have a return before it. Normally TeX ignores linebreaks, providing full paragraphs to ragged text. In this case it is necessary to pull the linebreak up one line to the end of the previous sentence.
Overfull hbox
[101] Overfull \hbox (9.11617pt too wide) in paragraph at lines 860--861 []\LY1/brm/m/n/10 Windows, \LY1/brm/m/it/10 see \LY1/brm/m/n/10 X WinAn 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 and/or was deleted.
198
Missing package
! LaTeX Error: File `paralisy.sty' not found. Type X to quit or <RETURN> to proceed, or enter new name. (Default extension: sty) Enter file name: When you use the \usepackage command to request LaTeX to use a certain package, it will look for a file with the specified name and the filetype .sty. In this case the user has mistyped the name of the paralist package, so it's easy to fix. However, if you get the name right, but the package is not installed on your machine, you will need to download and install it before continuing. If you don't want to affect the global installation of the machine, you can simply download from Internet the necessary .sty file and put it in the same folder of the document you are compiling.
Package babel Warning: No hyphenation patterns were loaded for the language X
Although this is a warning from the Babel package and not from LaTeX, this error is very common and (can) give some strange hyphenation (word breaking) problems in your document. Wrong hyphenation rules can decrease the neatness of your document. Package babel Warning: No hyphenation patterns were loaded for (babel) the language `Latin' (babel) I will use the patterns loaded for \language=0 instead. This can happen after the usage of: (see LaTeX/Internationalization) \usepackage[latin]{babel} The solution is not difficult, just install the used language in your LaTeX distribution.
199
References
[1] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ nag [2] http:/ / www. ctan. org/ tex-archive/ support/ lacheck [3] http:/ / baruch. ev-en. org/ proj/ chktex/
Lengths
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Lengths
200 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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
Lengths
201
Units
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.[1]
Abbreviation pt mm cm in ex em Definition a point is 1/72.27 inch, that means about 0.0138 inch or 0.3515 mm. 1 a millimeter a centimeter inch roughly the height of an 'x' in the current font roughly the width of an 'M' (uppercase) in the current font 2.84 28.4 72.27 undefined, depends on the font used undefined, depends on the font used Value in points (pt)
a big point is 1/72 inch, that means about 0.0139 inch or 0.3527 mm. 1.00375 pica didt (1157 didt = 1238 points) ccero (12 didt) scaled point (65536sp per point) 12 1.07 12.84 0.000015
Box lengths
A box in TeX is characterized by three lengths: depth height width See Boxes.
Length manipulation
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} \settodepth{\mylength}{some text} \settoheight{\mylength}{some text}
Lengths 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, latxpar must be placed before minus. To print a length, you can use the \the command: \the\textwidth
202
plainTeX
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 .
Lengths 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.
203
Fixed-length spaces
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 the a double linebreak is still in vertical mode if it does not expand to characters.
Lengths % WRONG! Some words. \bigskip Let's continue. %% CORRECT! Some words. \bigskip Let's continue.
204
Rubber/Stretching lengths
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 The same way, you can stretch vertically: \maketitle \vspace{ \tableofcontents \stretch{1} } Some comments. \vspace{ \stretch{1} }
x x x
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
Examples
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}%
Lengths \usebox{\mytitletext}% }
205
References
[1] http:/ / www. uz. ac. zw/ science/ maths/ latex/ ltx-86. html [2] http:/ / www. uz. ac. zw/ science/ maths/ latex/ ltx-86. html
Counters
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Counters
206 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Counters are an essential part of LaTeX: they allow you to control the numbering mechanism of everything (sections, lists, captions, etc.).
Counters
207
Counter manipulation
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] 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
There are several ways to get access to a counter. \theNameOfTheNewCounter will print the formatted string related to 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 \newcounter\mycounter do abide by the backslash rule.
Counter style
Each counter also has a default format that dictates how it is displayed whenever LaTeX needs to print it. Such formats are specified using internal LaTeX commands:
Counters
208
Command
Example 1, 2, 3 ... a, b, c ... A, B, C ... i, ii, iii ... I, II, III ... Aimed at footnotes; prints a sequence of symbols.
Custom enumerate
See the List Structures chapter.
Custom sectioning
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}
Counters \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
209
Boxes
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Boxes
210 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] LaTeX builds up its pages by pushing around boxes. At first, each letter is a little box, which is then glued to other letters to form words. These are again glued to other words, but with special glue, which is elastic so that a series of words can be squeezed or stretched as to exactly fill a line on the page. Admittedly, this is a very simplistic description of what really happens, but the point is that TeX operates with glue and boxes. Letters are not the only things that can be boxes. One can put virtually everything into a box, including other boxes. Each box will then be handled by LaTeX as if it were a single letter.
Boxes The past chapters have already dealt with some boxes, although they weren't described as such. The tabular environment and the \includegraphics , for example, both produce a box. This means that one can easily arrange two tables or images side by side. You just have to make sure that their combined width is not larger than the \textwidth .
211
Framebox
The command \framebox works exactly the same as \makebox , but it draws a box around the text. \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 Im 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.
Boxes 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}
212
framed
An alternative to these approaches is the usage of the framed environment (you will need to include the framed package to use it). This provides an easy way to box a paragraph within a document: \usepackage{framed} % ... \begin{framed} This is an easy way to box text within a document! \end{framed} You can do it manually with a parbox.
Raisebox
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.
This should print 3 boxes on the same line. Do not put another linebreak between the \fbox , otherwise you will put the following \fbox in another paragraph on another line.
Boxes
213
Savebox
A \savebox is a reference to a box filled with contents. You can use it as a way to print or manipulate something repeatedly. \newsavebox{boxname} \savebox{boxname}{some content} \usebox{boxname} The command \newsavebox creates a placeholder for storing a text; the command \savebox stores the specified text in this placeholder, and does not display anything in the document; and \usebox recalls the content of the placeholder into the document.
Rotatebox
See Rotations.
Fancybox
the fancybox package provides additional boxes. \doublebox \ovalbox \shadowbox
214
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
215 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
216
Rules
The \rule command in normal use produces a simple black box: \rule[depth]{width}{height} The depth, width and height parameters are explained in the Boxes chapter. Here is an example: \rule{3mm}{.1pt}% \rule[-1mm]{5mm}{1cm}% \rule{3mm}{.1pt}% \rule[1mm]{1cm}{5mm}% \rule{3mm}{.1pt}
Struts
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
LaTeX provides the \hrulefill command, which work like a stretched horizontal space. See the Lengths chapter.
217
Technical Texts
Mathematics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Mathematics
218 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] One of the greatest motivating forces for Donald Knuth when he began developing the original TeX system was to create something that allowed simple construction of mathematical formulas, whilst looking professional when printed. The fact that he succeeded was most probably why TeX (and later on, LaTeX) became so popular within the scientific community. Typesetting mathematics is one of LaTeX's greatest strengths. It is also a large topic due to the existence of so much mathematical notation.
Mathematics If your document requires only a few simple mathematical formulas, plain LaTeX has most of the tools that you will need. If you are writing a scientific document that contains numerous complicated formulas, the amsmath package[1] introduces several new commands that are more powerful and flexible than the ones provided by 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.
219
Mathematics environments
LaTeX needs to know beforehand that the subsequent text does indeed contain mathematical elements. This is because LaTeX typesets maths notation differently than normal text. Therefore, special environments have been declared for this purpose. They can be distinguished into two categories depending on how they are presented: text text formulas are displayed inline, that is, within the body of text where it is declared, for example, I can say that a + a = 2a within this sentence. displayed displayed formulas are separate from the main text. As maths require special environments, there are naturally the appropriate environment names you can use in the standard way. Unlike most other environments, however, there are some handy shorthands to declaring your formulas. The following table summarizes them:
Type Environment Requires LaTeX shorthand TeX shorthand Comment Inline (within text) formulas Displayed equations Displayed and automatically numbered equations
math
displaymath equation
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: 1. 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 2. Empty lines are not allowed. Only one paragraph per formula. 3. Each letter is considered to be the name of a variable and will be typeset as such. If you want to typeset normal text within a formula (normal upright font and normal spacing) then you have to enter the text using dedicated commands.
Mathematics
220
Symbols
Mathematics has many symbols! One of the most difficult aspects of learning LaTeX is remembering how to produce symbols. There are of course a set of symbols that can be accessed directly from the keyboard: + - = ! / ( ) [ ] < > | ' : Beyond those listed above, distinct commands must be issued in order to display the desired symbols. There are a great deal of 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 "The Comprehensive LaTeX Symbol List" in the external links section below.
Greek letters
Greek letters are commonly used in mathematics, and they are very easy to type in math mode. You just have to type the name of the letter after a backslash: if the first letter is lowercase, you will get a lowercase Greek letter, if the first letter is uppercase (and only the first letter), then you will get an uppercase letter. Note that some uppercase Greek letters look like Latin ones, so they are not provided by LaTeX (e.g. uppercase Alpha and Beta are just "A" and "B" respectively). Lowercase epsilon, theta, 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, \Phi Scroll down to #List of Mathematical Symbols for a complete list of Greek symbols.
Operators
An operator is a function that is written as a word: e.g. trigonometric functions (sin, cos, tan), logarithms and exponentials (log, exp). LaTeX has many of these defined as commands: \cos (2\theta) = \cos^2 \theta - \sin^2 \theta For certain operators such as limits, the subscript is placed underneath the operator: \lim_{x \to \infty} \exp(-x) = 0 For the modular operator there are two commands: \bmod and \pmod :
Mathematics
To use operators which are not pre-defined, such as argmax, see custom operators
It is also possible to use the \choose command without the amsmath package: \frac{n!}{k!(n-k)!} = {n \choose k}
displayed mathematics. The \tfrac and \dfrac commands force the use of the respective styles, \textstyle and \displaystyle . Similarly, the \tbinom and \dbinom commands typeset the binomial coefficient. Another way to write fractions is to use the \over command without the amsmath package: {n! \over k!(n-k)!} = {n \choose k}
For relatively simple fractions, it may be more aesthetically pleasing to use powers and indices: ^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:
Mathematics
222
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 Alternatively, the nicefrac package provides the \nicefrac command, whose usage is similar to \sfrac .
Continued fractions
Continued fractions should be written using \cfrac command[3]: \begin{equation} x = a_0 + \cfrac{1}{a_1 + \cfrac{1}{a_2 + \cfrac{1}{a_3 + \cfrac{1}{a_4} } } } \end{equation}
Roots
The \sqrt command creates a square root surrounding an expression. It accepts an optional argument specified in square brackets ([ and ]) to change magnitude: \sqrt{\frac{a}{b}}
\sqrt[n]{1+x+x^2+x^3+\ldots} Some people prefer writing the square root "closing" it over its content. This method arguably makes it more clear 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}}
The new style is on left, the old one on right
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
Mathematics right. Unfortunately this code won't work if you want to use multiple roots: if you try to write
223 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 \LetLtxMacro{\oldsqrt}{\sqrt} % makes all sqrts closed \renewcommand{\sqrt}[1][]{% \def\DHLindex{#1}\mathpalette\DHLhksqrt} \def\DHLhksqrt#1#2{% \setbox0=\hbox{$#1\oldsqrt[\DHLindex]{#2\,}$}\dimen0=\ht0 \advance\dimen0-0.2\ht0 \setbox2=\hbox{\vrule height\ht0 depth -\dimen0}% {\box0\lower0.71pt\box2}} $\sqrt[a]{b} \quad \oldsqrt[a]{b}$ However this requires the \usepackage{letltxmacro} package
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 \bigoplus \bigcup \bigsqcup \int [3] \prod \bigotimes \bigcap \bigvee \oint [3] \coprod \bigodot \biguplus \bigwedge \iint [3]
\iiint
\iiiint
\idotsint
[3]
For more integral symbols, including those not included by default in the Computer Modern font, try the esint package. The \substack command[3] 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:
Mathematics
224 \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 [4].
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
Automatic sizing
Very often mathematical features will differ in size, in which case the delimiters surrounding the expression should vary accordingly. This can be done automatically using the \left , \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
Mathematics
225
Manual sizing
In certain cases, the sizing produced by the \left and \right commands may not be desirable, or you may simply want finer control over the delimiter sizes. In this case, the \big , \Big , \bigg and \Bigg modifier commands may be used: ( \big( \Big( \bigg( \Bigg(
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. \left and \right will give errors if the left and right appear on different lines.
To specify alignment of columns in the table, use starred version[5]: \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:
Mathematics
226
Environment name Surrounding delimiter pmatrix [3] [5] centers columns by default
Notes
pmatrix* bmatrix
allows to specify alignment of columns in optional parameter centers columns by default allows to specify alignment of columns in optional parameter centers columns by default allows to specify alignment of columns in optional parameter centers columns by default allows to specify alignment of columns in optional parameter centers columns by default allows to specify alignment of colums in optional parameter
[3] [5]
bmatrix* Bmatrix
[3] [5]
Bmatrix* vmatrix
[3] [5]
vmatrix* Vmatrix
[3] [5]
Vmatrix*
When writing down arbitrary sized matrices, it is common to use horizontal, vertical and diagonal triplets of dots (known as ellipses) to fill in certain columns and rows. These can be specified using the \cdots , \vdots and \ddots respectively: A_{m,n} = \begin{pmatrix} a_{1,1} & a_{1,2} & \cdots & a_{1,n} \\ a_{2,1} & a_{2,2} & \cdots & a_{2,n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m,1} & a_{m,2} & \cdots & a_{m,n} \end{pmatrix} In some cases you may want to have finer control of the alignment within each column, or want to insert lines between columns or rows. This can be achieved using the array environment, which is essentially a math-mode version of the tabular environment, which requires that the columns be pre-specified: \begin{array}{c|c} 1 & 2 \\ \hline 3 & 4 \end{array}
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}
Mathematics
227
Formatted text
Using the \text is fine and gets the basic result. Yet, there is an alternative that offers a little more flexibility. You may recall the introduction of font formatting commands, such as \textrm , \textit , \textbf , etc. These commands format the argument accordingly, e.g., \textbf{bold text} gives bold text. These commands are equally valid within a maths environment to include text. The added benefit here is that you can have better control over the font formatting, rather than the standard text achieved with \text . 50 \textrm{ apples} \times 100 \textbf{ apples} = \textit{lots of apples}^2
Mathematics
228
\mathnormal{} \mathrm{}
Fraktur
The maths formatting commands can be wrapped around the entire equation, and not just on the textual elements: they only format letters, numbers, and uppercase Greek, and the rest of the maths syntax is ignored. To bold lowercase Greek or other symbols use the \boldsymbol command[3]; 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[3] (poor mans 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
So what to do when you run out of symbols and fonts? Well the next step is to use accents:
Mathematics
229
a' \hat{a} \grave{a} \dot{a} \not{a} \overrightarrow{AB} a''' \overline{aaa} \breve{a} [3] \dddot{a} \widehat{AAA} \tilde{a}
a'' \bar{a} \acute{a} \ddot{a} \mathring{a} \overleftarrow{AB} a'''' \check{a} \vec{a} \ddddot{a} [3]
\widetilde{AAA} \underline{a}
Color
The package xcolor, described in Colors, allows us to add color to our equations. For example, k={\color{red}x}{\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 [8].
Mathematics There are other occasions where LaTeX has done its job correctly, but you just want to add some space, maybe to add a comment of some kind. For example, in the following equation, it is preferable to ensure there is a decent amount of space between the maths and the text. f(n) = \left\{ \begin{array}{l l} n/2 & \quad \text{if $n$ is even}\\ -(n+1)/2 & \quad \text{if $n$ is odd} \end{array} \right. This code produces errors with Miktex 2.9 and does not yield the results seen on the right. Use \textrm 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:
230
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 situationwhat is needed are some small spaces to be utilized in this type of instance, and that's what LaTeX provides:
Command Description small space Size 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
Mathematics The negative space may seem like an odd thing to use, however, it wouldn't be there if it didn't have some use! Take the following example: \left( \begin{array}{c} n \\ r \end{array} \right) = \frac{n!}{r!(n-r)!} The matrix-like expression for representing binomial coefficients is too padded. There is too much space between the brackets and the actual contents within. This can easily be corrected by adding a few negative spaces after the left bracket and before the right bracket. \left(\! \begin{array}{c} n \\ r \end{array} \!\right) = \frac{n!}{r!(n-r)!} In any case, adding some spaces manually should be avoided whenever possible: it makes the source code more complex and it's against the basic principles of a What You See is What You Mean approach. The best thing to do is to define some commands using all the spaces you want and then, when you use your command, you don't have to add any other space. Later, if you change your mind about the length of the horizontal space, you can easily change it modifying only the command you defined before. Let us use an example: you want the d of a dx in an integral to be in roman font and a small space away from the rest. If you want to type an integral like \int x \; \mathrm{d} x , you can define a command like this: \newcommand{\dd}{\; \mathrm{d}} in the preamble of your document. We have chosen \dd just because it reminds the "d" it replaces and it is fast to type. Doing so, the code for your integral becomes \int x \dd x . Now, whenever you write an integral, you just have to use the \dd instead of the "d", and all your integrals will have the same style. If you change your mind, you just have to change the definition in the preamble, and all your integrals will be changed accordingly.
231
Dots
LaTeX gives you several commands to insert dots 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:
Mathematics
232
Code
Output
Comment generic dots, 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. the output is similar to the previous one, but there is no automatic whitespace management; it works at a lower level. These dots are centered relative to the height of a letter. There is also the binary multiplication operator, \cdot, mentioned below. vertical dots diagonal dots inverse diagonal dots (requires the mathdots package) 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.
Code Output Comment for "dots with commas" for "dots with binary operators/relations" for "multiplication dots" for "dots with integrals"
A_1\dotso A_N
Mathematics
233
Relation Symbols
Symbol < \leq \ll \subset \subseteq \sqsubset \sqsubseteq \prec \preceq Script Symbol > \geq \gg \supset \supseteq \sqsupset \sqsupseteq \succ \succeq Script Symbol = \doteq \equiv \approx \cong \simeq \sim \propto \neq Script Symbol Script \parallel \asymp \vdash \in \smile \models \perp Symbol Script \nparallel \bowtie \dashv \ni \frown \notin \mid
Binary Operations
Symbol Script \pm \mp \times \div \ast \star \dagger \ddagger Symbol Script \cap \cup \uplus \sqcap \sqcup \vee \wedge \cdot Symbol Script \diamond \bigtriangleup \bigtriangledown \triangleleft \triangleright \bigcirc \bullet \wr Symbol Script \oplus \ominus \otimes \oslash \odot \circ \setminus \amalg
Mathematics
234
Delimiters
Symbol | \{ \uparrow \downarrow Script Symbol \| \} \Uparrow \Downarrow Script Symbol / \langle \lceil \lfloor Script Symbol Script \backslash \rangle \rceil \rfloor
Note: To use the Greek Letters in LaTeX that have the same appearance as their Roman equivalent, just use the Roman form: e.g., A instead of Alpha, B instead of Beta, etc.
Greek Letters
Symbol and and and and , and Script \Alpha and \alpha \Beta and \beta \Gamma and \gamma \Delta and \delta \Epsilon, \epsilon and \varepsilon \Zeta and \zeta \Eta and \eta and \Theta, \theta and \vartheta \Iota and \iota and \Kappa, \kappa and \varkappa \Lambda and \lambda \Mu and \mu Symbol and and and , , , and and , and and and , and and and and \Nu and \nu \Xi and \xi \Omicron and \omicron \Pi, \pi and \varpi \Rho, \rho and \varrho \Sigma, \sigma and \varsigma \Tau and \tau \Upsilon and \upsilon \Phi, \phi and \varphi \Chi and \chi \Psi and \psi \Omega and \omega Script
Other symbols
Symbol Script \partial \eth \hbar Symbol Script \imath \jmath \ell Symbol Script Symbol \Re \Im \wp Script \nabla \Box \infty Symbol Script \aleph \beth \gimel
Mathematics
235
Trigonometric Functions
Symbol Script Symbol \sin \cos \tan \cot Script \arcsin \arccos \arctan \arccot Symbol Script Symbol Script \sinh \cosh \tanh \coth \sec \csc
Summary
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 would be possible to keep going and going with math topics because it seems potentially limitless. However, with this tutorial, you should be able to get along sufficiently.
Notes
[1] [2] [3] [4] [5] [6] [7] [8] http:/ / www. ams. org/ publications/ authors/ tex/ amslatex http:/ / www. tex. ac. uk/ ctan/ macros/ latex/ contrib/ mh/ mathtools. pdf requires the package http:/ / hdl. handle. net/ 2268/ 6219 requires the package requires amsfonts or amssymb packages require mathrsfs package http:/ / tex. stackexchange. com/ questions/ 21598/ how-to-color-math-symbols
Further reading
meta:Help:Displaying a formula: Wikimedia uses a subset of LaTeX commands.
External links
LaTeX maths symbols (http://www.artofproblemsolving.com/Wiki/index.php/LaTeX:Symbols) detexify (http://detexify.kirelabs.org): applet for looking up LaTeX symbols by drawing them amsmath documentation (ftp://ftp.ams.org/pub/tex/doc/amsmath/amsldoc.pdf) LaTeX - The Student Room (http://www.thestudentroom.co.uk/wiki/LaTeX) The Comprehensive LaTeX Symbol List (http://www.ctan.org/tex-archive/info/symbols/comprehensive) LaTeX Mathematical Symbol (http://amath.colorado.edu/documentation/LaTeX/Symbols.pdf)
Advanced Mathematics
236
Advanced Mathematics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Advanced Mathematics
237 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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.
Advanced Mathematics
238
Equation numbering
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} 5^2 - 5 = 20 \end{equation} this references the 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 preamble will result in the equation number in the above example to be rendered in this way: (1.1..1). To remove the duplicate dot, add \numberwithin{equation}{subsection} : following command immediately after
\renewcommand{\theequation}{\thesection\arabic{equation}} For numbering scheme using \numberwithin{equation}{subsection} use: \renewcommand{\theequation}{\thesubsection\arabic{equation}} in the preamble of the document. Note: Though 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 .
Advanced Mathematics
239
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} + \underbrace{iy}_\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]:
Advanced Mathematics
240
\[ 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 [ & ]) specifies the subscript, and the mandatory argument (using { & }) specifies the superscript (this can be left empty). \[ A \xleftarrow{\text{this way}} B \xrightarrow[\text{or that way}]{} C \] For more extensible arrows, you must use mathtools package: \[ 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\\ \]
and for harpoons: \[ 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 \]
Advanced Mathematics The align is similar, but automatically numbers each line like the equation environment. Individual lines may be referred to by placing a \label{...} before the linebreak. 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 because 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. The following example illustrates the alignment rule of align*: \begin{align*} a & b & c & d & e & f & g & h & i & j \end{align*}
241
To force display style for equations inside this construct, use dcases environment[2]:
Advanced Mathematics
242
Often the second column consists mostly of normal text, to set it in normal roman font of the document use dcases* environment[2]: \[ f(x) = \begin{dcases*} x & when $x$ is even\\ -x & when $x$ is odd \end{dcases*} \]
Other environments
Although align and align* are the most useful, there are several other environments which may also be of interest:
Environment name eqnarray and eqnarray* multline and [1] multline* gather and [1] gather* flalign and [1] flalign* alignat and [1] alignat* Description Notes
Equation number aligned vertically with first line and not centered as with other environments.
Similar to align, but left aligns first equation column, and right aligns last column Takes an argument specifying number of columns. Allows to control explicitly the horizontal space between equations You can calculate the number of columns by counting & characters in a line, adding 1 and dividing the result by 2
There are also 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 gathered split [1] [1] [1] [1] Description Allows to gather few equations to be set under each other and assigned a single equation number Similar to align*, but used inside another displayed mathematics environment Similar to align, to be used inside another mathematics environment. Similar to alignat, and just as it, takes an additional argument specifying number of columns of equations to set.
aligned
alignedat
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}
Advanced Mathematics
243
Indented Equations
In order to indent an equation, you can set fleqn in the document class and then specify a certain value for \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}
Boxed Equations
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
Advanced Mathematics
244
\begin{align*} \Aboxed{ f(x) & = \int h(x)\, dx} \\ & = g(x) \end{align*}
Custom operators
Although many common operators are available in LaTeX, sometimes you will need to write your own, for example to typeset the argmax operator. The \operatorname and \operatorname* commands[1] display a 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 keep within the LaTeX ideal of markup to define a new operator. 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
Limits
There are defaults for placement of subscripts and superscripts. For example, limits for the lim operator are usually placed below the symbol, like this: \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 \limits command. Similarly one can put subscripts under a symbol that usually have them on the side: \begin{equation} \int_a^b x^2 \end{equation} Limits below and under: \begin{equation} \int\limits_a^b x^2 \end{equation}
To change default placement in all instances of summation-type symbol to the side add nosumlimits option to amsmath package. To change placement for integral symbols add intlimits to options and nonamelimits to change the default for named operators like det, min, lim...
Advanced Mathematics
245
It's 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.
Multiline subscripts
To produce multiline subscript use \substack command: \begin{equation} \prod_{\substack{ 1\le i \le n\\ 1\le j \le m}} M_{i,j} \end{equation}
Note that usage of this command doesn't change alignment, as would stopping and restarting the align environment. Also in this example, the command \shortintertext{} from the mathtools package could have been used instead of intertext to reduce the amount of vertical whitespace added between the lines.
Advanced Mathematics
246
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 over 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 as in this example, they have reached the \scriptstyle limit). If you wanted 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. However, 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. NB 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 \DeclareMathSizes{11}{19}{13}{9} % For \DeclareMathSizes{12}{20}{14}{10} % For size 12 text size size 10 11 text text
Advanced Mathematics
247
Short skips are used if the preceding line ends, horizontally, before the formula. These parameters must be set after \begin{document}.
Notes
[1] Requires the package [2] requires the package
Theorems
LaTeX
Theorems
248 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Theorems
249 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] 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.
Theorems
250
Basic theorems
First of all, make sure you have the amsthm package enabled: \usepackage{amsthm} The easiest is the following: \newtheorem{name}{Printed output} put it in the preamble. The first argument is the name you will use to reference it, the second argument is the output LaTeX will print whenever you use it. For example: \newtheorem{mydef}{Definition} will define the mydef environment; if you use it like this: \begin{mydef} Here is a new definition \end{mydef} It will look like this: Definition 3 Here is a new definition with line breaks separating it from the rest of the text.
Theorem counters
Often the counters are determined by section, for example "Theorem 2.3" refers to the 3rd theorem in the 2nd section of a document. In this case, specify the theorem as follows: \newtheorem{name}{Printed output}[numberby] where numberby 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.
Theorems
251
Proofs
The proof environment[1] can be used for adding the proof of a theorem. The basic usage is: \begin{proof} Here is my proof \end{proof} It just adds Proof in italics at the beginning of the text given as argument and a white square (Q.E.D symbol, also known as a tombstone) at the end of it. If you are writing in another language than English, just use babel with the right argument and the word Proof printed in the output will be translated accordingly; anyway, in the source the name of the environment remains proof. If you would like to manually name the proof, include the name in square brackets: \begin{proof}[Proof of important theorem] Here is my important proof \end{proof} If the last line of the proof is displayed math then the Q.E.D. symbol will appear on a subsequent empty line. To put the Q.E.D. symbol at the end of the last line, use the \qedhere command: \begin{proof} Here is my proof: \[ a^2 + b^2 = c^2 \qedhere \] \end{proof} 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
It adds the possibility to change the output of the environments defined by \newtheorem \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: using the
Theorems
252
stylename plain
Description
Appearance
Used for theorems, lemmas, propositions, etc. (default) Theorem 1. Theorem text. Definition 2. Definition text. Remark 3. Remark text.
definition Used for definitions and examples remark Used for remarks and notes
Custom styles
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
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{
Theorems \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}
253
Notes
[1] Requires the amsthm package
External links
amsthm documentation (ftp://ftp.ams.org/pub/tex/doc/amscls/amsthdoc.pdf)
Chemical Graphics
LaTeX
Chemical Graphics
254 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Chemical Graphics
255 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] chemfig [1] is a package used to draw 2D chemical structures. It is an alternative to ochem [2]. Whereas ochem requires Perl to draw chemical structures, chemfig uses the tikz [3] package to produce its graphics. chemfig is used by adding the following to the preamble: \usepackage{chemfig}
Chemical Graphics
256
Basic Usage
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>
<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.
Chemical Graphics
257
Skeletal Diagrams
Skeleton diagrams can be produced as follows: \chemfig{-[:30]-[:-30]-[:30]}
\chemfig{-[:30]=[:-30]-[:30]}
Rings
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
Lewis structures can be created by using the command \lewis{<electron angle><electron>,<atom>} within \chemfig{}.
Ions
For example, consider an acetate ion:
Chemical Graphics
258 \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}
Chemical Reactions
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
Chemical Graphics
259
Chemical Graphics
260
Advanced Graphics
For advanced commands and examples, refer to the chemfig manual introduction to the package can be found.
[4]
References
[1] [2] [3] [4] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ chemfig/ http:/ / www. 2k-software. de/ ingo/ ochem. html http:/ / az. ctan. org/ pkg/ pgf http:/ / mirror. ctan. org/ macros/ latex/ contrib/ chemfig/ chemfig_doc_en. pdf
Algorithms
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Algorithms
261 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] LaTeX has a variety of packages that can help to format algorithms and "pseudocode". These packages provide stylistic enhancements over a uniform style (i.e., typewriter fonts) so that constructs such as loops or conditionals are visually separated from other text. If you want to typeset real source code or to include source code in you document, you should have a look at Source Code Listings.
Algorithms
262
263
More details are in the manual hosted on the ctan website [5].
Algorithms
264
If-statements
There are three forms of this construct \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.
For-loops
There are two forms \For{<condition>} <text> \EndFor \ForAll{<condition>} <text> \EndFor A traditional "for" loop. The method of iteration is usually described in the first argument, e.g. \For{$i = 1 \to 10$} \State $i \gets i + 1$ \EndFor
While-loops
\While{<condition>} <text> \EndWhile \While{$i \leq 10$} \State i=i+1; \EndWhile
Algorithms
265
Infinite loops
\Loop <text> \EndLoop
Precondition
\Require <text>
Postcondition
\Ensure <text>
Functions
\Function{<name>}{<params>} <body> \EndFunction
Returning values
\Return <text> 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.
Algorithms 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
266
Algorithm numbering
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}
Algorithms
267
List of algorithms
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.
Algorithms
268
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:
Algorithms \[ \( \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;
269
Algorithms \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 \NumberProgramsfalse Package page [6] Package documentation [7] setting \NumberProgramstrue and numbering turned off with
270
References
[1] [2] [3] [4] [5] [6] [7] http:/ / mirror. ctan. org/ tex-archive/ macros/ latex/ contrib/ algorithms/ algorithms. pdf http:/ / mirror. ctan. org/ tex-archive/ macros/ latex/ contrib/ algorithms/ http:/ / ieeexplore. ieee. org/ xpl/ periodicals. jsp (http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ IEEEtran) http:/ / mirror. ctan. org/ tex-archive/ macros/ latex/ contrib/ algorithm2e/ doc/ algorithm2e. pdf http:/ / www. ctan. org/ pkg/ program http:/ / mirror. ctan. org/ macros/ latex/ contrib/ program/ program-doc. pdf
The official manual for the algorithms package, Rogrio Brito (2009), http://mirrors.ctan.org/macros/ latex/contrib/algorithms/algorithms.pdf
271
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
272 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
273
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}
274
Supported languages
It supports the following programming languages:
ABAP ACSL Ada Algol Ant IDL inform Java JVMIS ksh PL/I Plasm POV Prolog Promela Python R Reduce
Assembler2 Lisp Awk bash Basic2 C4 C++ Caml Clean Cobol Comal csh Delphi Eiffel Elan erlang Euphoria Fortran GCL Gnuplot Haskell HTML Logo make
Mathematica1 Rexx Matlab Mercury MetaPost Miranda Mizar ML Modelica3 Modula-2 MuPAD NASTRAN Oberon-2 OCL Octave Oz Pascal Perl PHP RSL Ruby S SAS Scilab sh SHELXL Simula SQL tcl TeX VBScript Verilog VHDL VRML 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 1. 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. 2. Specification of the dialect is mandatory for these languages (e.g. language={[x86masm]Assembler} ). 3. Modelica is supported via the dtsyntax package available here [1]. 4. Some languages have optional dialects. Like C has (ANSI, Handel, Objective, Sharp) the listings manual, p12 [2].
275
Settings
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} 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 frame=single, % adds a frame around the code 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 is a lot more options, check the official documentation.
276
Style definition
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=customasm]{sched.s} The C part will print as
277
Encoding issue
Unfortunately, listings does not support multi-byte encoding for source code. You cannot input UTF-8 source files nor use special characters in your listing environment while your document is saved as UTF-8. The extendedchar option only works for 8-bits encodings such as latin1. Some languages only make use of some diacritics over the traditional ASCII characters (A-Za-z). In that case you may want to turn all accented characters to the blank ASCII one. You can automate this task with tools like sed. sed -i -e 's//a/g' -e 's//e/g' source.c Nonetheless, commenting source code in a language other than English is often considered bad practice. English normally allows your source code to be widely understood and maintained.
Customizing captions
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} } % ...
278
References
A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses [3]. Details and documentation about the Listings package can be found at its CTAN website [4].
References
[1] [2] [3] [4] https:/ / code. google. com/ p/ dtsyntax/ ftp:/ / ftp. tex. ac. uk/ tex-archive/ macros/ latex/ contrib/ listings/ listings. pdf http:/ / mirror. hmc. edu/ ctan/ macros/ latex/ contrib/ listings/ listings. pdf http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ listings/
Linguistics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Linguistics
279 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] There are a number of LaTeX packages available for writing linguistics papers. Various packages have been created for enumerated examples, syntactic trees, OT tableaux, feature matrices, IPA fonts, and many other applications. Some packages such as the tipa package are effectively standard within the field, while others will vary by author preference. Some recommended packages[1]: Glosses: gb4e;
Linguistics IPA symbols: tipa; OT Tableaux: OTtablx; Syntactic trees: qtree + tree-dvips (for drawing arrows); Alternatively, xyling is very powerful but not as user friendly as qtree; The xy [2] package itself has a steep learning curve, but allows a lot of control; for simplest trees use the xymatrix feature and arrows; tikz-qtree [3] has the same syntax as qtree, but uses PGF/TikZ, which allows more options for drawing arrows, etc. Depdency trees and bubble parses: The TikZ-depdendency [4] package provides a high-level, convenient interface to draw dependency graphs. It is based on PGF/TikZ but does not require prior knowledge of TikZ in order to be used productively. Attribute-Value Matrices (AVMs): avm [5] John Frampton's expex: expex [6]
280
Enumerated examples
There are several commonly used packages for creating the kinds of numbered examples that are used in linguistics publications.
gb4e
The gb4e package[7] is called with: \usepackage{gb4e} IMPORTANT: If you use gb4e package, let it be the last \usepackage call in the document's preamble. Otherwise you may get exceeded parameter stack size error. Examples for this package are placed within the exe environment, and each example is introduced with the \ex command. \begin{exe} \ex This is an example. \end{exe} produces:
Multiple examples can be included within the environment, and each will have its own number. \begin{exe} \ex This is the first example. \ex This is the second example. \ex This is the third. \end{exe} produces:
Linguistics \begin{exe} \ex \begin{xlist} \ex This is a sub-example. \ex This is a second sub-example. \ex \begin{xlist} \ex This is a sub-sub-example. \ex This is a second sub-sub-example. \end{xlist} \end{xlist} \end{exe} produces:
281
For notating acceptability judgments, the \ex command can take an optional argument. When including a judgment marker, the corresponding sentence must be surrounded by braces. \begin{exe} \ex This sentence is grammatical English. \ex[*] {This sentence English in ungrammatical is.} \end{exe} produces:
Referencing examples in text works as it does in normal LaTeX documents. See the labeling and cross-referencing section for more details. \begin{exe} \ex\label{ex1} Godzilla destroyed the city. \ex\label{ex2} Godzilla roared. \end{exe} Sentence (\ref{ex1}) contains two arguments, but (\ref{ex2}) contains only one. Further details can be found in the full documentation available here [8].
Linguistics
282
lingmacros
The lingmacros package[9] created by Emma Pease is an alternate method for example numbering. This package uses two main commands, \enumsentence and \eenumsentence . The former is used for singleton examples, while the latter command is used for nested examples. \enumsentence{This is an example.}
\enumsentence{This is the first example.} \enumsentence{This is the second example.} \enumsentence{This is the third.}
Multiply nested examples make use of the normal LaTeX list environments. \eenumsentence{\item This is a sub-example. \item This is a second sub-example. \item \begin{enumerate} \item This is sub-sub-example. \item This is a second sub-sub-example. \end{enumerate} } produces:
Syntactic trees
Often, linguists will have to illustrate the syntactic structure of a sentence. One device for doing this are syntactic trees. Unfortunately, trees look very different in different grammar formalisms, and different LaTeX packages are suited for different formalisms.
Constituent trees
While there are several packages for drawing syntactic trees available for LaTeX, this article focuses on the qtree and xyling packages.
Linguistics qtree Drawing trees with qtree is relatively straightforward. First, the qtree package has to be included in the document's preamble: \usepackage{qtree} A new tree is started using the \Tree command, each (sub-)tree is indicated by brackets [ ]. The root of a (sub-)tree is always preceded by a ., leaf nodes are simply expressed by their labels. For example, the following code \Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ] produces this syntactic tree as output:
283
Note that the spaces before the closing brackets are mandatory. By default, qtree centers syntactic trees on the page. This behaviour can be turned off by either specifying the behaviour when loading the package \usepackage[nocenter]{qtree} % do not center trees or via the command \qtreecenterfalse % do not center trees from here on anywhere in the document. The effect of the latter can be undone by using the command \qtreecentertrue % center trees from here on IMPORTANT: If you use gb4e package, let it be the last \usepackage call in the document's preamble. Otherwise you may get exceeded parameter stack size error.
Linguistics tikz-qtree Using the same syntax as qtree, tikz-qtree is another easy-to-use alternative for drawing syntactic trees. For simple trees, tikz-qtree is completely interchangable with qtree. However, some of qtree's advanced features are implemented in a different way, or not at all. On the other hand, tikz-qtree provides other features such as controlling the direction of the tree's growth (top to bottom, left to right etc.) or different styles for edges. To use the tikz-qtree package for drawing trees, put the following into the document's preamble: \usepackage{tikz} \usepackage{tikz-qtree} The syntax of tikz-qtree and result when drawing a simple tree is the same as for qtree. \Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ]
284
Note that, other than for qtree, trees are not centered by default. To center them, put them into a centered environment: \begin{center} \Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ] \end{center} For setting the style of trees, tikz-qtree provides the \tikzset command. For example, to make a tree grow from left to right instead of from top to bottom, use the following code: \tikzset{grow'=right} % make trees grow from left to right \tikzset{every tree node/.style={anchor=base west}} % allign nodes of the tree to the left (west) \Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ]
The above code changes the default orientation for all trees that are defined after \tikzset commands. To only change the direction of a single tree, it has to be put into a \tikzpicture environment:
Linguistics \begin{tikzpicture} % all changes only affect trees within this environment \tikzset{grow'=right} % make trees grow from left to right \tikzset{every tree node/.style={anchor=base west}} % allign nodes of the tree to the left (west) \Tree [.S [.NP LaTeX ] [.VP [.V is ] [.NP fun ] ] ] \end{tikzpicture}
285
Dependency Trees
Dependency trees can take multiple visual forms. Commonly, they quite resemble phrase structure trees. Alternatively, they can be captured by brackets drawn above running text. Two-dimensional Dependency Trees These can be either achieved using the fairly universal drawing package TikZ, like so: % In the preamble: \usepackage{tikz} % In the document: \begin{tikzpicture} \node (is-root) {is} [sibling distance=3cm] child { node {this} } child { node {tree} [sibling distance=1.5cm] child { node {an} } child { node {example} } child { node {.} } child[missing] }; \path (is-root) +(0,-2.5\tikzleveldistance) node {\textit{This is an example tree.}}; \end{tikzpicture} which gives you the following drawing:
Linguistics TikZ has the advantage that it allows for generating PDF directly from the LaTeX source, without need for any detour of compiling to DVI using latex, and then converting to PDF probably via PS using tools such as dvips and ps2pdf. Latter is the case of another package based on the package xy, namely xyling. The code for a similar tree using xyling might look like: % In the preamble: \usepackage{xytree} % In the document: \Tree{ & \K{is}\B{dl}\B{drr} \\ \K{this} &&& \K{tree}\B{dll}\B{dl}\B{dr} \\ & \K{an} & \K{example} && \K{.} } \medskip \textit{This is an example tree.} which gives you a drawing like this:
286
Dependency Trees as Brackets above Text One way to typeset dependency brackets above running text is using the package xytree. It gives you fairly good control of how the brackets are typeset but requires compiling the LaTeX code to DVI (and perhaps converting to PDF using the tools dvips and ps2pdf later). An example code: % In the preamble: \usepackage{xytree} % In the document: \xytext{ \xybarnode{Peter} &~~~& \xybarnode{and} \xybarconnect(UL,U){-2}"_{\small conj}" \xybarconnect(UR,U){2}"^{\small conj}" &~~~& \xybarnode{Mary} &~~~& \xybarnode{bought} \xybarconnect[8](UL,U){-4}"_{\small subj}" \xybarconnect[13]{6}"^{\small punct}"
Linguistics \xybarconnect[8](UR,U){4}"^{\small obj}" &~~~& \xybarnode{a} &~~~& \xybarnode{car} \xybarconnect(UL,U){-2}"_{\small det}" &~~~& \xybarnode{.} } results in:
287
Dependency Trees using TikZ-dependency [4] The package provides high level commands to design and style dependency graphs. To draw a graph, you only need to create a dependency environment, write the text of the sentence within the deptext environment and use depedge commands to draw the edges. Global and local optional parameters can be used to style and fine tune the looks of the graph, as shown in the following example: % In the preamble: \usepackage{tikz-dependency} % In the document: \begin{dependency}[theme = simple] \begin{deptext}[column sep=1em] A \& hearing \& is \& scheduled \& on \& the \& issue \& today \& . \\ \end{deptext} \deproot{3}{ROOT} \depedge{2}{1}{ATT} \depedge[edge start x offset=-6pt]{2}{5}{ATT} \depedge{3}{2}{SBJ} \depedge{3}{9}{PU} \depedge{3}{4}{VC} \depedge{4}{8}{TMP} \depedge{5}{7}{PC} \depedge[arc angle=50]{7}{6}{ATT} \end{dependency} This code snippet would produce the following result:
Linguistics
288
Glosses
With gb4e
Below, it is explained how to a glossed example in your document using package gb4e . To create a glossed example, use the normal exe environment. But after the \ex tag, introduce the example and its gloss using \gll and the translation after it with \trans tag. \begin{exe} \ex \gll \\ cat.NOM eat.3.SG.PRS sour-cream.ACC\\ \trans `The cat eats sour cream' \end{exe} The code will produce the following output:
Vertically aligned glosses are separated by spaces, so if it's necessary to include a space in part the gloss, simply enclose the connected parts inside braces. \begin{exe} \ex \gll Pekka pel\"astyi karhusta.\\ Pekka {became afraid} bear.ELA\\ \trans `Pekka became afraid because of the/a bear.' \end{exe}
Linguistics
289
With lingmacros
The lingmacros package uses the \shortex command to introduce glossed examples inside the \enumsentence and \eenumsentence commands. This command takes four arguments and builds off the normal tabular environment. Its first argument specifies the number of columns in the gloss. The second and third arguments give the text and its gloss respectively, and items within each column are divided by the usual & tabular separator. The fourth argument is the translation. \enumsentence{\shortex{3} {Pekka & pel\"astyi & karhu-sta.} {Pekka & became afraid & bear.ELA} {`Pekka became afraid because of the/a bear.'} }
IPA characters
The tipa package is the standard LaTeX package for International Phonetic Alphabet symbols. \usepackage{tipa} There are two methods for getting IPA symbols into a document. The first way is to use the IPA environment. \begin{IPA} text in IPA format here \end{IPA} This method is useful for long stretches of text that need to be in IPA. Alternatively, there is the \textipa command that will format the text in its argument into IPA. This command is similar to other font typesetting commands. \textipa{text in IPA format here}
Basic symbols
The IPA format works by translating ASCII characters into corresponding IPA symbols. Lower case letters are rendered as usual, \textipa{abcdefghijklmnopqrstuvwxyz}
Punctuation marks that are normally used in LaTeX are also rendered faithfully in the IPA environment. \textipa{! * + = ? . , / [ ] ( ) ` ' | ||} produces:
290
In addition, there are a number of special macros for representing symbols that don't have other associations, some of which are listed here. For a complete list see the official TIPA Manual[11]. The \; macro preceding a capital letter produces a small caps version of the letter. \textipa{\;A \;B \;E \;G \;H \;I \;L \;R \;Y} produces:
The \: macro produces retroflex symbols. \textipa{\:d \:l \:n \:r \:s \:t \:z} gets you:
The \! macro produces implosive symbols and the bilabial click. \textipa{\!b \!d \!g \!j \!G \!o} gets you:
References
[1] (http:/ / jones. ling. indiana. edu/ ~mdickinson/ 08/ latex/ slides. pdf) LaTeX for Linguists presentation [2] http:/ / ctan. org/ tex-archive/ macros/ generic/ diagrams/ xypic/ xy [3] http:/ / ctan. org/ pkg/ tikz-qtree [4] http:/ / sourceforge. net/ projects/ tikz-dependency/ [5] http:/ / nlp. stanford. edu/ ~manning/ tex/ avm. sty [6] http:/ / www. math. neu. edu/ ling/ tex/ [7] (http:/ / ctan. mines-albi. fr/ help/ Catalogue/ entries/ gb4e. html/ ) The gb4e package on CTAN [8] http:/ / ctan. mackichan. com/ macros/ latex/ contrib/ gb4e/ gb4e-doc. pdf [9] (http:/ / ctan. org/ tex-archive/ macros/ latex209/ contrib/ trees/ tree-dvips) The lingmacros package on CTAN [10] http:/ / mirrors. ibiblio. org/ pub/ mirrors/ CTAN/ macros/ latex209/ contrib/ trees/ tree-dvips/ lingmacros-manual. pdf [11] (http:/ / uit. no/ getfile. php?PageId=874& FileId=165) TIPA manual
External links
LaTeX for Linguists (http://www.essex.ac.uk/linguistics/external/clmt/latex4ling/) The qtree package for drawing syntactic trees. (http://www.ling.upenn.edu/advice/latex/qtree/) The gb4e package page on CTAN. (http://www.ctan.org/tex-archive/macros/latex/contrib/gb4e/)
291
Special Pages
Indexing
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Indexing
292 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Especially useful in printed books, an index is an alphabetical list of words and expressions with the pages of the book upon which they are to be found. LaTeX supports the creation of indices with its package makeidx, and its support program makeindex, called on some systems makeidx.
Indexing
293
Using makeidx
To enable the indexing feature of LaTeX, the makeidx package must be loaded in the preamble with: \usepackage{makeidx} and the special indexing commands must be enabled by putting the \makeindex command into the input file preamble. This should be done within the preamble, since it tells LaTeX to create the files needed for indexing. To tell LaTeX what to index, use \index{key} where key is the index entry and does not appear in the final layout. You enter the index commands at the points in the text that you want to be referenced in the index, likely near the reason for the key. For example, the text To solve various problems in physics, it can be advantageous to express any arbitrary piecewise-smooth function as a Fourier Series composed of multiples of sine and cosine functions. can be re-written as To solve various problems in physics, it can be advantageous to express any arbitrary piecewise-smooth function as a Fourier Series \index{Fourier Series} composed of multiples of sine and cosine functions. to create an entry called 'Fourier Series' with a reference to the target page. Multiple uses of \index with the same key on different pages will add those target pages to the same index entry. To show the index within the document, merely use the command \printindex It is common to place it at the end of the document. The default index format is two columns. The showidx package that comes with LaTeX prints out all index entries in the right margin of the text. This is quite useful for proofreading a document and verifying the index.
Compiling indices
When the input file is processed with LaTeX, each \index command writes an appropriate index entry, together with the current page number, to a special file. The file has the same name as the LaTeX input file, but a different extension (.idx). This .idx file can then be processed with the makeindex program. Type in the command line: makeindex filename Note that filename is without extension: the program will look for filename.idx and use that. You can optionally pass filename.idx directly to the program as an argument. The makeindex program generates a sorted index with the same base file name, but this time with the extension .ind. If now the LaTeX input file is processed again, this sorted index gets included into the document at the point where LaTeX finds \printindex . The index created by latex with the default options may not look as nice or as suitable as you would like it. To improve the looks of the index makeindex comes with a set of style files, usually located somewhere in the tex directory structure, usually below the makeindex subdirectory. To tell makeindex to use a specific style file, run it with the command line option:
Indexing makeindex -s <style file> filename If you use a GUI for compiling latex and index files, you may have to set this in the options. Here are some configuration tips for typical tools: MakeIndex settings in WinEdt Say you want to add an index style file named simpleidx.ist Texify/PDFTexify: OptionsExecution ModesAccessoriesPDFTeXify, add to the Switches: --mkidx-option="-s simpleidx.ist" MakeIndex alone: OptionsExecution ModesAccessoriesMakeIndex, add to command line: -s simpleidx.ist
294
Sophisticated indexing
Below are examples of \index entries:
Example Index Entry hello, 1 Peter, 3 Sam, 2 Lin, 7 Jenny, 3 Joe, 5 cole, 4 Peter, see hello Comment Plain entry Subentry under 'hello' Formatted entry Same as above Formatted page number Same as above Handling of accents Cross-references
\index{hello} \index{hello!Peter} \index{Sam@\textsl{Sam}} \index{Lin@\textbf{Lin}} \index{Jenny|textbf} \index{Joe|textit} \index{ecole@\'ecole} \index{Peter|see{hello}} \index{Jen|seealso{Jenny}} Subentries
If some entry has subsections, these can be marked off with !. For example, \index{encodings!input!cp850} would create an index entry with 'cp850' categorized under 'input' (which itself is categorized into 'encodings'). These are called subsubentries and subentries in makeidx terminology. Controlling sorting In order to determine how an index key is sorted, place a value to sort by before the key with the @ as a separator. This is useful if there is any formatting or math mode, so one example may be \index{F@$\vec{F}$} so that the entry in the index will show as ' ' but be sorted as 'F'.
Indexing Changing page number style To change the formatting of a page number, append a | and the name of some command which does the formatting. This command should only accept one argument. For example, if on page 3 of a book you introduce bulldogs and include the command \index{bulldog} and on page 10 of the same book you wish to show the main section on bulldogs with a bold page number, use \index{bulldog|textbf} This will appear in the index as bulldog, 3, 10 If you use texindy in place of makeindex, the classified entries will be sorted too, such that all the bolded entries will be placed before all others by default. Multiple pages To perform multi-page indexing, add a |( and |) to the end of the \index command, as in \index{Quantum Mechanics!History|(} In 1901, Max Planck released his theory of radiation dependant on quantized energy. While this explained the ultraviolet catastrophe in the spectrum of blackbody radiation, this had far larger consequences as the beginnings of quantum mechanics. ... \index{Quantum Mechanics!History|)} The entry in the index for the subentry 'History' will be the range of pages between the two \index commands. Using special characters In order to place values with !, @, or |, which are otherwise escape characters, in the index, one must quote these characters in the \index command by putting a double quotation mark (") in front of them, and one can only place a " in the index by quoting it (i.e., a key for " would be \index{""} ). This rule does not hold for \", so to put the letter in the index, one may still use \index{a@\"{a}} .
295
Abbreviation list
You can make a list of abbreviations with the package nomencl [1]. You may also be interested in using the glossaries package described in the Glossary chapter. To enable the Nomenclature feature of LaTeX, the nomencl package must be loaded in the preamble with: \usepackage[options ]{nomencl} \makenomenclature Issue the \nomenclature[prex]{symbol}{description} command for each symbol you want to have included in the nomenclature list. The best place for this command is immediately after you introduce the symbol for the rst time. Put \printnomenclature at the place you want to have your nomenclature list. Run LaTeX 2 times then makeindex filename.nlo -s nomencl.ist -o filename.nls
followed by running LaTeX once again. To add the abbreviation list to the table of content, intoc option can be used when declare the nomencl package, i.e. \usepackage[intoc]{nomencl}
Indexing instead of using the code in Adding Index to Table Of Contents section. The title of the list can be changed using the following command: \renewcommand{\nomname}{List of Abbreviations}
296
Multiple indices
If you need multiple indices you can use the package multind [2]. This package provides the same commands as makeidx, but now you also have to pass a name as the first argument to every command. \usepackage{multind} \makeindex{books} \makeindex{authors} ... \index{books}{A book to index} \index{authors}{Put this author in the index} ... \printindex{books}{The Books index} \printindex{authors}{The Authors index}
International indices
If you want to sort entries that have international characters (such as , , , , etc.) you may find that the sorting "is not quite right". In most cases the characters are treated as special characters and end up in the same group as @, or . In most languages that use Latin alphabet it's not correct.
Generating index
Unfortunately, current version of xindy and hyperref are incompatible. When you use textbf or textit modifiers, texindy will print error message:unknown cross-reference-class `hyperindexformat'! (ignored) and won't add those pages to index.
To generate international index file you have to use texindy instead of makeindex. xindy [3] is a much more extensible and robust indexing system than the makeindex system. For example, one does not need to write: \index{Lin@\textbf{Lin}} to get the Lin entry after LAN and before LZA, instead, it's enough to write \index{\textbf{Lin}} But what is much more important, it can properly sort index files in many languages, not only English. Unfortunately, generating indices ready to use by LaTeX using xindy is a bit more complicated than with makeindex. First, we need to know in what encoding the .tex project file is saved. In most cases it will be UTF-8 or ISO-8859-1, though if you live, for example in Poland it may be ISO-8859-2 or CP-1250. Check the parameter to the inputenc package.
Indexing Second, we need to know which language is prominently used in our document. xindy can natively sort indices in Albanian, Belarusian, Bulgarian, Croatian, Czech, Danish, Dutch, English, Esperanto, Estonian, Finnish, French, Georgian, German, Greek, Gypsy, Hausa, Hebrew, Hungarian, Icelandic, Italian, Klingon, Kurdish, Latin, Latvian, Lithuanian, Macedonian, Mongolian, Norwegian, Polish, Portuguese, Romanian, Russian, Serbian Slovak, Slovenian, Sorbian, Spanish, Swedish, Turkish, Ukrainian and Vietnamese, I don't know if other languages have similar problems, but with Polish, if your .tex is saved using UTF-8, the .ind produced by texindy will be encoded in ISO-8859-2 if you use only -L polish. While it's not a problem for entries containing polish letters, as LaTeX internally encodes all letters to plain ASCII, it is for accented letters at beginning of words, they create new index entry groups, if you have, for example an "rednia" entry, you'll get a "" encoded in ISO-8859-2 .ind file. LaTeX doesn't like if part of the file is in UTF-8 and part is in IS-8859-2. The obvious solution (adding -C utf8) doesn't work, texindy stops with ERROR: Could not find file "tex/inputenc/utf8.xdy" error. The fix this, you have to load the definiton style for the headings using -M switch: -M lang/polish/utf8 In the end we have to run such command: texindy -L polish -M lang/polish/utf8 filename.idx Additional way to fix this problem is use "iconv" to create utf8.xdy from latin2.xdy iconv -f latin2 -t utf8 latin2.xdy >utf8.xdy in folder /usr/share/xindy/tex/inputenc (You must have root privileges) xindy in kile To use texindy instead of makeindex in kile, you have to either redefine the MakeIndex tool in Settings Configure Kile... Tools Build, or define new tool and redefine other tools to use it (for example by adding it to QuickBuild). The xindy definition should look similar to this: General: Command: texindy Options: -L polish -M lang/polish/utf8 -I latex '%S.idx' Advanced: Type: Run Outside of Kile Class: Compile Source extension: idx Target extension: ind Target file: <empty> Relative dir: <empty> State: Editor Menu: Add tool to Build menu: Compile Icon: the one you like
297
Indexing
298
References
[1] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ nomencl/ [2] http:/ / www. tex. ac. uk/ cgi-bin/ texfaq2html?label=multind [3] http:/ / xindy. sourceforge. net/
Glossary
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Glossary
299 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Many technical documents use terms or acronyms unknown to the general population. It is common practice to add a glossary to make such documents more accessible. The glossaries package can be used to create glossaries. It supports multiple glossaries, acronyms, and symbols. This package replaces the glossary package and can be used instead of the nomencl package.[1] Users requiring a simpler solution should consider using the longtabu environment and hand-coding their entries.
Glossary
300
Jump start
Place \usepackage{glossaries} and \makeglossaries in your preamble (after \usepackage{hyperref} if present). Then define any number of \newglossaryentry and \newacronym glossary and acronym entries in your preamble (recommended) or before first use in your document proper. Finally add a \printglossaries call to locate the glossaries list within your document structure. Then pepper your writing with \gls{mylabel} macros (and similar) to simultaneously insert your predefined text and build the associated glossary. File processing must now include a call to makeglossaries followed by at least one further invocation of latex or pdflatex.
Using glossaries
To use the glossaries package, you have to load it explicitly: \usepackage{glossaries} if you wish to use xindy (recommended) for the indexing phase, as opposed to makeindex (the default), you need to specify the xindy option: \usepackage[xindy]{glossaries} For the glossary to show up in your Table of Contents, you need to specify the toc option: \usepackage[toc]{glossaries} See also Custom TOC Entry at the bottom of this page. Finally, place to following command in your document preamble in order to generate the glossary: \makeglossaries Any links in resulting glossary will not be "clickable" unless you load the glossaries package after the hyperref package. In addition, users who wish to make use of makeglossaries will need to have Perl installed this is not normally present by default on Microsoft Windows platforms. That said, makeglossaries simply provides a convenient interface to makeindex and xindy and is not essential.
Defining terms
To define a term in glossary you use \newglossaryentry macro: \newglossaryentry{<label>}{<settings>} <label> is a unique label used to identify an entry in glossary, <settings> are comma separated key=value pairs used to define an entry. For example, to define a computer entry:
Glossary \newglossaryentry{computer} { name=computer, description={is a programmable machine that receives input, stores and manipulates data, and provides output in a useful format} } The above example defines an entry that has the same label and entry name. This is not always the case as the next entry will show: \newglossaryentry{naiive} { name=na\"{\i}ve, description={is a French loanword (adjective, form of naf) indicating having or showing a lack of experience, understanding or sophistication} } When you define terms, you need to remember that they will be sorted by makeindex or xindy. While xindy is a bit more LaTeX aware, it does it by omitting latex macros (\"{\i} ) thus incorrectly sorting the above example as nave. makeindex won't fare much better, because it doesn't understand TeX macros, it will interpret the word exactly as it was defined, putting it inside symbol class, before words beginning with naa. Therefore it's needed to extend our example and specify how to sort the word: \newglossaryentry{naiive} { name=na\"{\i}ve, description={is a French loanword (adjective, form of naf) indicating having or showing a lack of experience, understanding or sophistication}, sort=naive } You can also specify plural forms, if they are not formed by adding s (we will learn how to use them in next section): \newglossaryentry{Linux} { description={is a generic term referring to the family of Unix-like computer operating systems that use the Linux kernel}, plural=Linuces } Or, for acronyms: \newacronym[longplural=Frames per Second]{FPS}{fpsLabel}{Frame per Second} This will avoid the wrong long plural: Frame per Seconds.
301
Defining symbols
Defined entries can also be symbols: \newglossaryentry{pi} { name={\ensuremath{\pi}}, circumference of circle to its diameter}, sort=pi } You can also define both a name and a symbol: \newglossaryentry{real number} { name={real number}, description={include both rational numbers, such as $42$ and $\frac{-23}{129}$, and irrational numbers, such as $\pi$ and the square root of two; or, a real number can be given by an infinite decimal representation, such as $2.4871773339\ldots$ where the digits continue in some way; or, the real numbers may be thought of as points on an infinitely long number line}, symbol={\ensuremath{\mathbb{R}}} } Note that not all glossary styles show defined symbols. description={ratio of
Glossary
302
Defining acronyms
To define a new acronym you use the \newacronym macro: \newacronym{<label>}{<abbrv>}{<full>} where <label> is the unique label identifying the acronym, <abbrv> is the abbreviated form of the acronym and <full> is the expanded text. For example: \newacronym{lvm}{LVM}{Logical Volume Manager} Defined acronyms can be put in separate list if you use acronym package option: \usepackage[acronym]{glossaries}
General references
A general reference is used with \gls command. If, for example, you have glossary entries defined as those above, you might use it in this way: \Gls{naiive} people don't know about alternative \gls{computer} operating systems: \glspl{Linux}, BSDs and GNU/Hurd.
Nave people don't know about alternative computer operating systems: Linuces, BSDs and GNU/Hurd. </pre>
Description of commands used in above example: \gls{<label>} This command prints the term associated with <label> passed as its argument. If the hyperref package was loaded before glossaries it will also be hyperlinked to the entry in glossary. \glspl{<label>} This command prints the plural of the defined therm, other than that it behaves in the same way as gls . \Gls{<label>} This command prints the singular form of the term with the first character converted to upper case. \Glspl{<label>} This command prints the plural form with first letter of the term converted to upper case. \glslink{<label>}{<alternate text>} This command creates the link as usual, but typesets the alternate text instead. It can also take several options which changes its default behavior (see the documentation).
Glossary
303
Referring acronyms
Acronyms behave a bit differently than normal glossary terms. On first use the \gls command will display "<full> (<abbrv>)". On subsequent uses only the abbreviation will be displayed. To reset the first use of an acronym use: \glsreset{<label>} or, if you want to reset the use status of all acronyms: \glsresetall
Custom Name
The name of the glossary section can be replaced with a custom name or translated to a different language: \renewcommand*{\glossaryname}{List of Terms} \deftranslation{Glossary}{List of Terms}
Glossary
304
References
[1] http:/ / www. ctan. org/ pkg/ nomencl [2] http:/ / mirror. ox. ac. uk/ sites/ ctan. org/ macros/ latex/ contrib/ glossaries/ glossaries-user. html#dx1-35001 [3] http:/ / mirror. ox. ac. uk/ sites/ ctan. org/ macros/ latex/ contrib/ glossaries/ glossaries-user. html#dx1-43001
The glossaries documentation, http://tug.ctan.org/tex-archive/macros/latex/contrib/glossaries/ Using LaTeX to Write a PhD Thesis, Nicola L.C. Talbot, (http://theoval.cmp.uea.ac.uk/~nlct/latex/thesis/ node25.html) glossaries FAQ, Nicola L. C. Talbot, glossaries FAQ (http://www.dickimaw-books.com/faqs/glossariesfaq. html) Glossaries, Nomenclature, Lists of Symbols and Acronyms, Nicola L. C. Talbot, link (http://www. latex-community.org/know-how/263-glossaries-nomenclature-lists-of-symbols-and-acronyms)
Bibliography Management
305
Bibliography Management
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Bibliography Management
306 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] For any academic/research writing, incorporating references into a document is an important task. Fortunately, LaTeX has a variety of features that make dealing with references much simpler, including built-in support for citing references. However, a much more powerful and flexible solution is achieved thanks to an auxiliary tool called BibTeX [5] (which comes bundled as standard with LaTeX). Recently, BibTeX has been succeeded by BibLaTeX, a tool configurable within LaTeX syntax.
Bibliography Management BibTeX provides for the storage of all references in an external, flat-file database. (BibLaTeX uses this same syntax.) This database can be referenced in any LaTeX document, and citations made to any record that is contained within the file. This is often more convenient than embedding them at the end of every document written; a centralized bibliography source can be linked to as many documents as desired (write once, read many!). Of course, bibliographies can be split over as many files as one wishes, so there can be a file containing sources concerning topic A (a.bib) and another concerning topic B (b.bib). When writing about topic AB, both of these files can be linked into the document (perhaps in addition to sources ab.bib specific to topic AB).
307
Embedded system
If you are writing only one or two documents and aren't planning on writing more on the same subject for a long time, maybe you don't want to waste time creating a database of references you are never going to use. In this case you should consider using the basic and simple bibliography support that is embedded within LaTeX. LaTeX provides an environment called thebibliography that you have to use where you want the bibliography; that usually means at the very end of your document, just before the \end{document} command. Here is a practical example: \begin{thebibliography}{9} \bibitem{lamport94} Leslie Lamport, \emph{\LaTeX: A Document Preparation System}. Addison Wesley, Massachusetts, 2nd Edition, 1994. \end{thebibliography} OK, so what is going on here? The first thing to notice is the establishment of the environment. thebibliography is a keyword that LaTeX recognizes as everything between the begin and end tags as being data for the bibliography. The mandatory argument, which I supplied after the begin statement, is telling LaTeX how wide the item label will be when printed. Note however, that the number itself is not the parameter, but the number of digits is. Therefore, I am effectively telling LaTeX that I will only need reference labels of one character in length, which ultimately means no more than nine references in total. If you want more than nine, then input any two-digit number, such as '56' which allows up to 99 references. Next is the actual reference entry itself. This is prefixed with the \bibitem{cite_key} command. The cite_key should be a unique identifier for that particular reference, and is often some sort of mnemonic consisting of any sequence of letters, numbers and punctuation symbols (although not a comma). I often use the surname of the first author, followed by the last two digits of the year (hence lamport94). If that author has produced more than one reference for a given year, then I add letters after, 'a', 'b', etc. But, you should do whatever works for you. Everything after the key is the reference itself. You need to type it as you want it to be presented. I have put the different parts of the reference, such as author, title, etc., on different lines for readability. These linebreaks are ignored by LaTeX. I wanted the title to be in italics, so I used the \emph{} command to achieve this.
Citations
To actually cite a given document is very easy. Go to the point where you want the citation to appear, and use the following: \cite{cite_key}, where the cite_key is that of the bibitem you wish to cite. When LaTeX processes the document, the citation will be cross-referenced with the bibitems and replaced with the appropriate number citation. The advantage here, once again, is that LaTeX looks after the numbering for you. If it were totally manual, then adding or removing a reference would be a real chore, as you would have to re-number all the citations by hand. Instead of WYSIWYG editors, typesetting systems like \TeX{}, \LaTeX{}, or \cite{lamport94} can be used.
Bibliography Management
308
Multiple citations
When a sequence of multiple citations are needed, you should use a single \cite{} command. The citations are then separated by commas. Note that you must not use spaces between the citations. Here's an example: \cite{citation01,citation02,citation03} The result will then be shown as citations inside the same brackets.
No cite
If you only want a reference to appear in the bibliography, but not where it is referenced in the main text, then the \nocite{} command can be used, for example: Lamport showed in 1995 something... \nocite{lamport95}. A special version of the command, \nocite{*}, includes all entries from the database, whether they are referenced in the document or not.
\citeyearpar{goossens93} (1993) \citealt{goossens93} \citealp{goossens93} \citetext{priv.\ comm.} Goossens et al. 1993 Goossens et al., 1993 (priv. comm.)
Using the standard LaTeX bibliography support, you will see that each reference is numbered and each citation corresponds to the numbers. The numeric style of citation is quite common in scientific writing. In other disciplines, the author-year style, e.g., (Roberts, 2003), such as Harvard is preferred, and is in fact becoming increasingly common within scientific publications. A discussion about which is best will not occur here, but a possible way to get such an output is by the natbib package. In fact, it can supersede LaTeX's own citation commands, as Natbib allows the user to easily switch between Harvard or numeric.
Bibliography Management The first job is to add the following to your preamble in order to get LaTeX to use the Natbib package: \usepackage[options]{natbib} Also, you need to change the bibliography style file to be used, so edit the appropriate line at the bottom of the file so that it reads: \bibliographystyle{plainnat}. Once done, it is basically a matter of altering the existing \cite commands to display the type of citation you want.
309
Natbib-compatible styles
Style plainnat abbrvnat unsrtnat apsrev rmpaps Provided Provided Provided REVTeX 4 home page REVTeX 4 home page Source Description natbib-compatible version of plain natbib-compatible version of abbrv natbib-compatible version of unsrt [1] natbib-compatible style for Physical Review journals [1] natbib-compatible style for Review of Modern Physics journals natbib-compatible style for IEEE publications natbib-compatible style for American Chemical Society journals natbib-compatible style for Royal Society of Chemistry journals
IEEEtranN TeX Catalogue entry [2] achemso rsc TeX Catalogue entry TeX Catalogue entry [3] [4]
Natbib options
Option round square curly angle colon comma authoryear numbers super sort Parentheses () (default) Square brackets [] Curly braces {} Angle brackets <> multiple citations are separated by semi-colons (default) multiple citations are separated by commas author year style citations (default) numeric citations superscripted numeric citations multiple citations are sorted into the order in which they appear in the references section Meaning
sort&compress as sort, compressing multiple numeric citations where possible longnamesfirst the first citation of any reference will use the starred variant (full author list), subsequent citations will use the abbreviated et al. style sectionbib nonamebreak for use with the chapterbib package. redefines \thebibliography to issue \section* instead of \chapter* keeps all the authors names in a citation on one line to fix some hyperref problems - causes overfull hboxes
The main commands simply add a t for 'textual' or p for 'parenthesized', to the basic \cite command. You will also notice how Natbib by default will compress references with three or more authors to the more concise 1st surname et al version. By adding an asterisk (*), you can override this default and list all authors associated with that citation. There are some other specialized commands that Natbib supports, listed in the table here. Keep in mind that for instance abbrvnat does not support \citet* and will automatically choose between all authors and et al..
Bibliography Management The final area that I wish to cover about Natbib is customizing its citation style. There is a command called \bibpunct that can be used to override the defaults and change certain settings. For example, I have put the following in the preamble: \bibpunct{(}{)}{;}{a}{,}{,} The command requires six mandatory parameters. 1. 2. 3. 4. The symbol for the opening bracket. The symbol for the closing bracket. The symbol that appears between multiple citations. This argument takes a letter:
310
n - numerical style. s - numerical superscript style. any other letter - author-year style. 5. The punctuation to appear between the author and the year (in parenthetical case only). 6. The punctuation used between years, in multiple citations when there is a common author. e.g., (Chomsky 1956, 1957). If you want an extra space, then you need {,~}. Some of the options controlled by \bibpunct are also accessible by passing options to the natbib package when it is loaded. These options also allow some other aspect of the bibliography to be controlled, and can be seen in the table (right). So as you can see, this package is quite flexible, especially as you can easily switch between different citation styles by changing a single parameter. Do have a look at the Natbib manual [5], it's a short document and you can learn even more about how to use it.
BibTeX
I have previously introduced the idea of embedding references at the end of the document, and then using the \cite command to cite them within the text. In this tutorial, I want to do a little better than this method, as it's not as flexible as it could be. I will concentrate on using BibTeX. A BibTeX database is stored as a .bib file. It is a plain text file, and so can be viewed and edited easily. The structure of the file is also quite simple. An example of a BibTeX entry: @article{greenwade93, author = "George D. Greenwade", title = "The {C}omprehensive {T}ex {A}rchive {N}etwork ({CTAN})", year = "1993", journal = "TUGBoat", volume = "14", number = "3", pages = "342--351" } Each entry begins with the declaration of the reference type, in the form of @type. BibTeX knows of practically all types you can think of, common ones are: book, article, and for papers presented at conferences, there is inproceedings. In this example, I have referred to an article within a journal. After the type, you must have a left curly brace '{' to signify the beginning of the reference attributes. The first one follows immediately after the brace, which is the citation key, or the BibTeX key. This key must be unique for all entries in your bibliography. It is this identifier that you will use within your document to cross-reference it to this entry. It is up to you as to how you wish to label each reference, but there is a loose standard in which you use the
Bibliography Management author's surname, followed by the year of publication. This is the scheme that I use in this tutorial. Next, it should be clear that what follows are the relevant fields and data for that particular reference. The field names on the left are BibTeX keywords. They are followed by an equals sign (=) where the value for that field is then placed. BibTeX expects you to explicitly label the beginning and end of each value. I personally use quotation marks ("), however, you also have the option of using curly braces ('{', '}'). But as you will soon see, curly braces have other roles, within attributes, so I prefer not to use them for this job as they can get more confusing. A notable exception is when you want to use characters with umlauts (, , etc), since their notation is in the format \"{o}, and the quotation mark will close the one opening the field, causing an error in the parsing of the reference. Using \usepackage[utf8]{inputenc} in the preamble to the .tex source file can get round this, as the accented characters can just be stored in the .bib file without any need for special markup. This allows a consistent format to be kept throughout the .bib file, avoiding the need to use braces when there are umlauts to consider. Remember that each attribute must be followed by a comma to delimit one from another. You do not need to add a comma to the last attribute, since the closing brace will tell BibTeX that there are no more attributes for this entry, although you won't get an error if you do. It can take a while to learn what the reference types are, and what fields each type has available (and which ones are required or optional, etc). So, look at this entry type reference [6] and also this field reference [7] for descriptions of all the fields. It may be worth bookmarking or printing these pages so that they are easily at hand when you need them.
311
Authors
BibTeX can be quite clever with names of authors. It can accept names in forename surname or surname, forename. I personally use the former, but remember that the order you input them (or any data within an entry for that matter) is customizable and so you can get BibTeX to manipulate the input and then output it however you like. If you use the forename surname method, then you must be careful with a few special names, where there are compound surnames, for example "John von Neumann". In this form, BibTeX assumes that the last word is the surname, and everything before is the forename, plus any middle names. You must therefore manually tell BibTeX to keep the 'von' and 'Neumann' together. This is achieved easily using curly braces. So the final result would be "John {von Neumann}". This is easily avoided with the surname, forename, since you have a comma to separate the surname from the forename. Secondly, there is the issue of how to tell BibTeX when a reference has more than one author. This is very simply done by putting the keyword and in between every author. As we can see from another example: @book{goossens93, author = "Michel Goossens and Frank Mittelbach and Alexander Samarin", title = "The LaTeX Companion", year = "1993", publisher = "Addison-Wesley", address = "Reading, Massachusetts" } This book has three authors, and each is separated as described. Of course, when BibTeX processes and outputs this, there will only be an 'and' between the penultimate and last authors, but within the .bib file, it needs the and's so that it can keep track of the individual authors.
Bibliography Management
312
Standard templates
Be careful if you copy the following templates, the % sign is not valid to comment out lines in bibtex files. If you want to comment out a line, you have to put it outside the entry. @article An article from a magazine or a journal. Required fields: author, title, journal, year. Optional fields: volume, number, pages, month, note. @article{Xarticle, author = "", title = "", journal = "", %volume = "", %number = "", %pages = "", year = "XXXX", %month = "", %note = "", } @book A published book Required fields: author/editor, title, publisher, year. Optional fields: volume/number, series, address, edition, month, note. @book{Xbook, author title publisher %volume %number %series %address %edition year %month %note } @booklet A bound work without a named publisher or sponsor. Required fields: title. Optional fields: author, howpublished, address, month, year, note. @booklet{Xbooklet, %author = "", title = "", %howpublished = "",
= = = = = = = = = = =
"", "", "", "", "", "", "", "", "XXXX", "", "",
Bibliography Management %address year %month %note } @conference Equal to inproceedings Required fields: author, title, booktitle, year. Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note. @conference{Xconference, author = "", title = "", booktitle = "", %editor = "", %volume = "", %number = "", %series = "", %pages = "", %address = "", year = "XXXX", %month = "", %publisher= "", %note = "", } @inbook A section of a book without its own title. Required fields: author/editor, title, chapter and/or pages, publisher, year. Optional fields: volume/number, series, type, address, edition, month, note. @incollection A section of a book having its own title. Required fields: author, title, booktitle, publisher, year. Optional fields: editor, volume/number, series, type, chapter, pages, address, edition, month, note. @inproceedings An article in a conference proceedings. Required fields: author, title, booktitle, year. Optional fields: editor, volume/number, series, pages, address, month, organization, publisher, note. @manual Technical manual Required fields: title. Optional fields: author, organization, address, edition, month, year, note. @mastersthesis Master's thesis = = = = "", "XXXX", "", "",
313
Bibliography Management Required fields: author, title, school, year. Optional fields: type (eg. "diploma thesis"), address, month, note. @mastersthesis{Xthesis, author = "", title = "", school = "", %type = "diploma thesis", %address = "", year = "XXXX", %month = "", %note = "", } @misc Template useful for other kinds of publication Required fields: none Optional fields: author, title, howpublished, month, year, note. @misc{Xmisc, %author = "", %title = "", %howpublished = "", %year = "XXXX", %month = "", %note = "", } @phdthesis Ph.D. thesis Required fields: author, title, year, school. Optional fields: address, month, keywords, note. @proceedings The proceedings of a conference. Required fields: title, year. Optional fields: editor, volume/number, series, address, month, organization, publisher, note. @techreport Technical report from educational, commercial or standardization institution. Required fields: author, title, institution, year. Optional fields: type, number, address, month, note. @techreport{Xtreport, author = "", title = "", institution = "", %type = "", %number = "", %address = "",
314
Bibliography Management year %month %note } @unpublished An unpublished article, book, thesis, etc. Required fields: author, title, note. Optional fields: month, year. = "XXXX", = "", = "",
315
@incollection{Abedon1994,
Bibliography Management
author = "Abedon, S. T.", title = "Lysis and the interaction between free phages and infected cells", pages = "397--405", booktitle = "Molecular biology of bacteriophage T4", editor = "Karam, Jim D. Karam and Drake, John W. and Kreuzer, Kenneth N. and Mosig, Gisela and Hall, Dwight and Eiserling, Frederick A. and Black, Lindsay W. and Kutter, Elizabeth and Carlson, Karin and Miller, Eric S. and Spicer, Eleanor", publisher = "ASM Press, Washington DC", year = "1994" }
316
If you have to cite a website you can use @misc, for example: @misc{website:fermentas-lambda, author = "Fermentas Inc.", title = "Phage Lambda: description \& restriction map", month = "November", year = "2008", url = "http://www.fermentas.com/techinfo/nucleicacids/maplambda.htm" } The note field comes in handy if you need to add unstructured information, for example that the corresponding issue of the journal has yet to appear: @article{blackholes, author="Rabbert Klein", title="Black Holes and Their Relation to Hiding Eggs", journal="Theoretical Easter Physics", publisher="Eggs Ltd.", year="2010", note="(to appear)" }
Bibliography styles are files recognized by BibTeX that tell it how to format the information stored in the .bib file when processed for output. And so the first command listed above is declaring which style file to use. The style file in this instance is plain.bst (which comes as standard with BibTeX). You do not need to add the .bst extension when using this command, as it is assumed. Despite its name, the plain style does a pretty good job (look at the output of this tutorial to see what I mean). The second command is the one that actually specifies the .bib file you wish to use. The ones I created for this tutorial were called sample1.bib, sample2.bib, . . ., samplen.bib, but once again, you don't include the file extension. At the moment, the .bib file is in the same directory as the LaTeX document too. However, if your .bib file was elsewhere (which makes sense if you intend to maintain a centralized database of references for all your research), you need to specify the path as well, e.g \bibliography{/some/where/sample}.
Bibliography Management Now that LaTeX and BibTeX know where to look for the appropriate files, actually citing the references is fairly trivial. The \cite{ref_key} is the command you need, making sure that the ref_key corresponds exactly to one of the entries in the .bib file. If you wish to cite more than one reference at the same time, do the following: \cite{ref_key1, ref_key2, ..., ref_keyN}.
317
(Extensions are optional, if you put them note that the bibtex command takes the AUX file as input.) After the first LaTeX run, you will see errors such as: LaTeX Warning: Citation `lamport94' on page 1 undefined on input line 21. ... LaTeX Warning: There were undefined references. The next step is to run bibtex on that same LaTeX source (or more precisely the corresponding AUX file, however not on the actual .bib file) to then define all the references within that document. You should see output like the following: This is BibTeX, Version 0.99c (Web2C 7.3.1) The top-level auxiliary file: latex_source_code.aux The style file: plain.bst Database file #1: sample.bib The third step, which is invoking LaTeX for the second time will see more errors like "LaTeX Warning: Label(s) may have changed. Rerun to get cross-references right.". Don't be alarmed, it's almost complete. As you can guess, all you have to do is follow its instructions, and run LaTeX for the third time, and the document will be output as expected, without further problems. If you want a pdf output instead of a dvi output you can use pdflatex instead of latex as follows: 1. 2. 3. 4. pdflatex latex_source_code.tex bibtex latex_source_code.aux pdflatex latex_source_code.tex pdflatex latex_source_code.tex
(Extensions are optional, if you put them note that the bibtex command takes the AUX file as input.) Note that if you are editing your source in vim and attempt to use command mode and the current file shortcut (%) to process the document like this: 1. :! pdflatex % 2. :! bibtex % You will get an error similar to this: 1. I couldn't open file name 'current_file.tex.aux'
Bibliography Management It appears that the file extension is included by default when the current file command (%) is executed. To process your document from within vim, you must explicitly name the file without the file extension for bibtex to work, as is shown below: 1. 2. 3. 4. :! :! :! :! pdflatex % bibtex %:r (without file extension, it looks for the AUX file as mentioned above) pdflatex % pdflatex %
318
However, it is much easier to install the Vim-LaTeX plugin from here [21]. This allows you to simply type \ll when not in insert mode, and all the appropriate commands are automatically executed to compile the document. Vim-LaTeX even detects how many times it has to run pdflatex, and whether or not it has to run bibtex. This is just one of the many nice features of Vim-LaTeX, you can read the excellent Beginner's Tutorial [9] for more about the many clever shortcuts Vim-LaTeX provides. Another option exists if you are running Unix/Linux or any other platform where you have make [10]. Then you can simply create a Makefile and use vim's make command or use make in shell. The Makefile would then look like this: latex_source_code.pdf: latex_source_code.tex latex_source_code.bib pdflatex latex_source_code.tex bibtex latex_source_code.aux pdflatex latex_source_code.tex pdflatex latex_source_code.tex
Bibliography styles
Below you can see three styles available with LaTeX:
plain
abbrv
Bibliography Management
319
alpha
To number the references in order of appearance, rather than alphabetical order use ieeetr \bibliographystyle{ieeetr}
Style Name Author Name Format Reference Format plain unsrt abbrv alpha abstract acm Homer Jay Simpson Homer Jay Simpson H. J. Simpson Homer Jay Simpson Homer Jay Simpson Simpson, H. J. #ID# #ID# #ID# Sim95 Simpson-1995a #ID# Simpson, 1995 Simpson1995 Simpson 1995 Sorting by author as referenced by author by author
authordate1 Simpson, Homer Jay apa named Simpson, H. J. (1995) Homer Jay Simpson
Web page http:/ / www. cs. stir. ac. uk/ ~kjt/ software/ latex/ showbst. html contains more examples. Examples given in PDF format http:/ / amath. colorado. edu/ documentation/ LaTeX/ reference/ faq/ bibstyles. pdf More info can also be found on http://amath.colorado.edu/documentation/LaTeX/reference/faq/bibstyles.html LaTeX Bibliography Style Database http:/ / bst. maururu. net/ provides more than 2000 styles which can be searched by the journal title.
program.
Bibliography Management
320
Bibliography Management For babelbib to take effect, a bibliography style supported by it - one of babplain, babplai3, babalpha, babunsrt, bababbrv, and bababbr3 - must be used: \bibliographystyle{babplain} \bibliography{sample}
321
Helpful tools
Literatur-Generator [18] FAST and EASY to create your own Bibliographie (Bibtex, Endnote, Din 1505, ...). The Literatur-Generator is totally free and you do not need a registration to use the Literatur-Generator. Mendeley [19] Mendeley is cost-free academic software for managing PDFs which can manage a bibliography in Open Office and read BibTeX. Zotero Zotero is a free and open reference manager working as a Firefox plugin capable of importing and exporting bib files. JabRef [30] is a Java program (under the GPL license) which lets you search many bibliographic databases such as Medline, Citeseer, IEEEXplore and arXiv and feed and manage your BibTeX local databases with your selected articles. Based on BiBTeX, JabRef can export in many other output formats such as html, MS Word or EndNote. It can be used online without being installed (http:// jabref.sourceforge.net/jws/jabref.jnlp) Referencer [21] Referencer is a Gnome application to organise documents or references, and ultimately generate a BibTeX bibliography file.
JabRef [20]
Literatur-Generator
Citavi [22] Commercial software (with size-limited free demo version) which even searches libraries for citations and keeps all your knowledge in a database. Export of the database to all kinds of formats is possible. Works together with MS Word and Open Office Writer. Moreover plug ins for browsers and Acrobat Reader exist to automatically include references to your project.
Bibliography Management bibliographer [23](broken link) Bibliographer is a BibTeX bibliography database editor which aims to be easy to use. Its features include linking files to your records with indexing and searching support. The interface is designed for the easy navigation of your bibliography, and double clicking a record will open the linked file. cb2Bib [24] The cb2Bib is a tool for rapidly extracting unformatted, or unstandardized bibliographic references from email alerts, journal Web pages, and PDF files.
322
BibDesk
KBibTeX [25] KBibTeX is a BibTeX editor for KDE to edit bibliographies used with LaTeX. Features include comfortable input masks, starting web queries (e. g. Google or PubMed) and exporting to PDF, PostScript, RTF and XML/HTML. As KBibTeX is using KDE's KParts technology, KBibTeX can be embedded into Kile or Konqueror. KBib [26] Another BibTeX editor for KDE. It has similar capabilities, and slightly different UI. Features include BibTeX reference generation from PDF files, plain text, DOI, arXiv & PubMed IDs. Web queries to Google Scholar, PubMer, arXiv and a number of other services are also supported. Bibwiki [27] Bibwiki is a Specialpage for MediaWiki to manage BibTeX bibliographies. It offers a straightforward way to import and export bibliographic records. BibDesk [28] BibDesk is a bibliographic reference manager for Mac OS X. It features a very usable user interface and provides a number of features like smart folders based on keywords and live tex display. CiteULike [29] CiteULike is a free online service to organise academic papers. It can export citations in BibTeX format, and can "scrape" BibTeX data from many popular websites. Bibtex [30] Bibtex is a DokuWiki plugin that allows for the inclusion of bibtex formatted citations in DokuWiki pages and displays them in APA format. Note: This Plugins is vulnerable to an XSS attack -> http://www. dokuwiki.org/plugin:bibtex BibSonomy [31] A free social bookmark and publication management system based on BibTeX. Synapsen [32] Hypertextual Card Index / Reference Manager with special support for BiBTeX / biblatex, written in Java. Ebib [33] a BibTeX database manager for Emacs, well resolved and never more than a few keystrokes away.
Summary
Although it can take a little time to get to grips with BibTeX, in the long term, it's an efficient way to handle your references. It's not uncommon to find .bib files on websites that people compile as a list of their own publications, or a survey of relevant works within a given topic, etc. Or in those huge, online bibliography databases, you often find BibTeX versions of publications, so it's a quick cut-and-paste into your own .bib file, and then no more hassle! Having all your references in one place can be a big advantage. And having them in a structured form, that allows customizable output is another one. There are a variety of free utilities that can load your .bib files, and allow you to view them in a more efficient manner, as well as sort them and check for errors.
Bibliography Management
323
Or, if you are using BibTeX, your references will be saved in a .bib file, and your TeX document will include the bibliography by these commands: \bibliographystyle{plain} \bibliography{mybibtexfile} Both of these examples will create a chapter-like (or section-like) output showing all your references. But even though the resulting References looks like a chapter or section, it will not be handled quite the same: it will not appear in the Table of Contents.
Using tocbibind
The most comfortable way of adding your bibliography to the table of contents is to use the dedicated package tocbibind that works with many standard document classes. Simply include this code in the preamble of your document: \usepackage[nottoc]{tocbibind} This will include the Bibliography in the Table of Contents without numbering. If you want to have proper numbering, include the following code in the preamble: \usepackage[nottoc,numbib]{tocbibind} The tocbibind package can also handle including the List of Figures, List of Tables and the Table of Contents itself in the Table of Contents. It has many options for numbering, document structure etc. to fit almost any scenario. See the tocbibind CTAN page [34] for detailed documentation.
Other methods
As unnumbered item If you want your bibliography to be in the table of contents, just add the following two lines just before the thebibliography environment: \clearpage \addcontentsline{toc}{chapter}{Bibliography} (OR \addcontentsline{toc}{section}{Bibliography} if you're writing an article) The first line just terminates the current paragraph and page. If you are writing a book, use \cleardoublepage to match the style used. The second line will add a line in the Table of Contents (first option, toc), it will be like the ones created by chapters (second option, chapter), and the third argument will be printed on the corresponding line in the Table of Contents; here Bibliography was chosen because it's the same text the thebibliography environment will automatically write when you use it, but you are free to write whatever you like. If you are using separate bib file, add these lines between \bibliographystyle and \bibliography. If you use hyperref package, you should also use \phantomsection command to enable hyperlinking from the table of contents to bibliography. \cleardoublepage \phantomsection \addcontentsline{toc}{chapter}{Bibliography} This trick is particularly useful when you have to insert the bibliography in the Table of Contents, but it can work for anything. When LaTeX finds the code above, it will record the info as described and the current page number, inserting a new line in the Contents page.
Bibliography Management As numbered item If you instead want bibliography to be numbered section or chapter, you'll likely use this way: \cleardoublepage % This is needed if the book class is used, to place the anchor in the correct page, % because the bibliography will start on its own page. % Use \clearpage instead if the document class uses the "oneside" argument \renewcommand*{\refname}{} % This will define heading of bibliography to be empty, so you can... \section{Bibliography} % ...place a normal section heading before the bibliography entries. \begin{thebibliography}{99} ... \end{thebibliography} Another even easier solution is to use \section inside of the \renewcommand block: \renewcommand{\refname}{\section{Sources}} % Using "Sources" as the title of the section \begin{thebibliography}{99} ... \end{thebibliography} You may wish to use \renewcommand*{\refname}{\vspace*{-1em}} \vspace*{-1em} to counteract the extra space the blank \refname inserts. Note: Use \bibname instead of \refname if you use the book or report class. followed by
324
BibLaTeX
As we said before, BibLaTeX is widely considered the `successor' of BibTeX. Intended as a full replacement for BibTeX, it is more configurable in its output and provides a multitude of new styles (for output) and fields (for the database) that can be used in a document. For now, refer to its comprehensive documentation on CTAN [35].
Multiple bibliographies
Using multibib
This package is for multiple Bibliographies for different sections in your work. For example, you can generate a bibliography for each chapter You can find information about the package on CTAN[36]
Bibliography Management
325
Using bibtopic
The bibtopic-Package[37] is created to differ the citations on more files, so that you can divide the bibliography into more parts. \documentclass[11pt]{article} \usepackage{bibtopic} \begin{document} \bibliographystyle{alpha} \section{Testing} Lets cite all the books: \cite{ColBenh:93} and \cite{Munt:93}; and an article: \cite{RouxSmart:95}. File books.bib is use for this listing: \begin{btSect}{books} \section{References from books} \btPrintCited \end{btSect} Here, the articles.bib is used, and the listing is in plain-format instead pf the standard alpha. \begin{btSect}[plain]{articles} \section{References from articles} \btPrintCited \section{Articles not cited} \btPrintNotCited \end{btSect} Just print all entries here with \btPrintAll \begin{btSect}[plain]{internet} \section{References from the internet} \btPrintAll \end{btSect} \end{document}
Bibliography Management
[17] [18] [19] [20] [21] [22] [23] [24] [25] [26] [27] [28] [29] [30] [31] [32] [33] [34] [35] [36] [37] http:/ / scholar. google. de/ scholar_preferences?hl=en& lr=& output=search http:/ / literatur-generator. de/ http:/ / mendeley. com http:/ / www. zotero. org/ http:/ / icculus. org/ referencer/ index. html http:/ / www. citavi. ch http:/ / bibliographer. homelinux. net/ http:/ / www. molspaces. com/ cb2bib/ http:/ / www. unix-ag. uni-kl. de/ ~fischer/ kbibtex/ http:/ / users. tpg. com. au/ thachly/ kbib/ http:/ / www. mediawiki. org/ wiki/ Extension:Bibwiki http:/ / bibdesk. sourceforge. net/ http:/ / www. citeulike. org/ http:/ / stat. genopole. cnrs. fr/ ~cambroise/ doku. php?id=softwares:dokuwikibibtexplugin http:/ / www. bibsonomy. org/ http:/ / www. verzetteln. de/ synapsen/ http:/ / ebib. sourceforge. net/ http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ tocbibind http:/ / www. ctan. org/ pkg/ biblatex http:/ / ctan. org/ pkg/ multibib http:/ / ctan. org/ pkg/ bibtopic
326
This page uses material from Andy Roberts' Getting to grips with LaTeX (http:/ / www. andy-roberts. net/ writing/ latex) with permission from the author.
More Bibliographies
LaTeX
More Bibliographies
327 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
More Bibliographies
328 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] This is a gentle introduction to using some of the bibliography functionality available to LaTeX users beyond the BibTeX basics. This introduction won't be discussing how to create new styles or packages but rather how to use some existing ones. It is worth noting that Harvard, for example, is a citation style. It is associated with an alphabetical reference list secondarily ordered on date, but the only strictly defined element of Harvard style is the citation in author-date format.
More Bibliographies
329
Natbib
Natbib is a package created by Patrick Daly as a replacement for the cite.sty package when author-date citation styles are required. Natbib provides three associated bibliography styles: plainnat abbrvnat unsrtnat which correspond to the three styles available by default in BibTeX where you have a plain numbered style, an abbreviated numbered style and an unsorted numbered style. Alongside these new styles is an extended set of citation commands to provide flexible citation formats. These are \citet[]{} and \citep[]{} each of which has a number of variants.
The Preamble
All Natbib styles require that you load the package in your document preamble. So, a skeleton LaTeX file with Natbib might look like this: \documentclass[]{article} \usepackage[round]{natbib} \begin{document} Document body text with citations.
More Bibliographies \bibliographystyle{plainnat} \bibliography{myrefs} \end{document} Options Options available with Natbib can be specified in the brackets on the \usepackage command. Among them are:
Option round square curly angle semicolon colon comma authoryear numbers super sort () [] {} <> separate citations with ; as semicolon separate with commas author-year citations numeric citations superscript citations multiple citations are ordered as in bibliography Effect
330
sort&compress as sort but number ranges are compressed and hyphenated compress number ranges are compressed and hyphenated but only where the 'natural' sort produces a continuous range
longnamesfirst first citation is full author list and subsequent citations are abbreviated sectionbib nonamebreak merge elide mcite allows multiple bibliographies in the same document forces all author names onto one line merges a citation with a previous citation elides any repeated elements in merged references ignore merge
Clearly some of these options require explanation but that will be achieved via examples below. For now, we just note that they can be passed through \usepackage[]{} in the preamble of your LaTeX file.
Citation
Basic Citation Commands
To cite with Natbib, use the commands \citet or \citep in your document. The "plain" versions of these commands produced abbreviated lists in the case of multiple authors but both have * variants which result in full author listings. I have assumed the use of the round option in these examples. \citet and \citet* The \citet command is used for textual citations, that is to say that author names appear in the text outside of the parenthetical reference to the date of publication. This command can take options for chapter, page numbers etc. Here are examples
More Bibliographies
331
produces Erds et al. (1965) produces Erds et al. (1965, chapter 2) produces Erds et al. (1965, pp. 10-12)
\citet*[see][chap. 2]{Erdos65} produces Erds , Heyting and Brouwer (see 1965, chap. 2)
\citep and \citep* The \citep command is used where the author name is to appear inside the parentheses alongside the date.
\citep{Erdos65} \citep[chapter 2]{Erdos65} \citep[pp. 10-12]{Erdos65} produces (Erds et al. 1965) produces (Erds et al. 1965, chapter 2) produces (Erds et al. 1965, pp. 10-12)
\citep*[see][chap. 2]{Erdos65} produces (Erds , Heyting and Brouwer see 1965, chap. 2)
More Bibliographies
332
333
Special Documents
Letters
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Letters
334 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Sometimes the mundane things are the most painful. However, it doesn't have to be that way because of evolved, user-friendly templates. Thankfully, LaTeX allows for very quick letter writing, with little hassle.
Letters
335
A sample letter.
Here is the example's code: \documentclass{letter} \usepackage{hyperref} \signature{Joe Bloggs} \address{21 Bridge Street \\ Smallville \\ Dunwich DU3 4WE} \begin{document} \begin{letter}{Director \\ Doe \& Co \\ 35 Anthony Road \\ Newport \\ Ipswich IP3 5RT} \opening{Dear Sir or Madam:} I am writing to you on behalf of the Wikipedia project (http://www.wikipedia.org/), an endeavour to build a fully-fledged multilingual encyclopaedia in an entirely open manner, to ask for permission to use your copyrighted material. % The \ldots command produces dots in a way that will not upset
Letters % the typesetting of the document. \ldots That said, allow me to reiterate that your material will be used to the noble end of providing a free collection of knowledge for everyone; naturally enough, only if you agree. If that is the case, could you kindly fill in the attached form and post it back to me? We shall greatly appreciate it. Thank you for your time and consideration. I look forward to your reply. \closing{Yours Faithfully,} \ps{P.S. You can find the full text of GFDL license at \url{http://www.gnu.org/copyleft/fdl.html}.} \encl{Copyright permission form} \end{letter} \end{document} To move the closing and signature parts to the left, insert the following before \begin{document}: \longindentation=0pt The amount of space to the left can be adjusted by increasing the 0pt.
336
Envelopes
Using the envlab package
The envlab package provides customization to the \makelabels command, allowing the user to print on any of an assortment of labels or envelope sizes. For example, beginning your LaTeX file the following way produces a document which includes the letter and a business-size (#10) envelope on the following page. \documentclass{letter} \usepackage[businessenvelope]{envlab} \makelabels Refer to the envlab user guide [1] for more information about this capable package. Note that the envlab package has issues displaying characters outside the base ASCII character set, see this debian bug report [2] for more information.
Letters
337
\begin{document}
FROM-NAME
FROM-STREET ADDRESS
\vspace{1.0in}\large \setlength\parindent{3.6in}
TO-NAME
TO-STREET ADDRESS
\end{document}
Printing
The above will certainly take care of the spacing but the actual printing is between you and your printer. One user reports that printing envelopes created with envlab is relatively painless. If you use the geometry package, you may find the following commands useful for printing the envelope. $ pdflatex envelope.tex $ pdf2ps envelope.pdf $ lpr -o landscape envelope.ps Alternatively, you can use the latex dvi output driver. In the first line, dvips command converts the .dvi file produced by latex into a .ps (PostScript) file. In the second line, the PostScript file is sent to the printer.
Letters $ latex envelope.tex && dvips -t unknown -T 9.5in,4.125in envelope.dvi $ lpr -o landscape envelope.ps It is reported that pdflatex creates the right page size but not dvips despite what it says in the geometry manual. It will never work though unless your printer settings are adjusted to the correct page style. These settings depend on the printer filter you are using and in CUPS might be available on the lpr command line if you are masochistic.
338
Windowed envelopes
An alternative to separately printing addresses on envelopes is to use the letter class from the KOMA package. It supports additional features like folding marks and the correct address placement for windowed envelopes. Using the scrlttr2 document class from the KOMA package the example letter code is: % koma_env.tex \documentclass[a4paper]{scrlttr2} \usepackage{lmodern} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage[english]{babel} \usepackage{url}
\setkomavar{fromname}{Joe Bloggs} \setkomavar{fromaddress}{21 Bridge Street \\ Smallville \\ Dunwich DU3 4WE} \setkomavar{fromphone}{0123 45679} \begin{document} \begin{letter}{Director \\ Doe \& Co \\ 35 Anthony Road \\ Newport \\ Ipswich IP3 5RT} \KOMAoptions{fromphone=true,fromfax=false} \setkomavar{subject}{Wikipedia} \setkomavar{customer}{2342} \opening{Dear Sir or Madam,} I am writing to you on behalf of the Wikipedia project (\url{http://www.wikipedia.org/}), an endeavour to build a fully-fledged multilingual encyclopaedia in an entirely open manner, to ask for permission to use your copyrighted material. \ldots That said, allow me to reiterate that your material will be used to the noble end of providing a free collection of knowledge for everyone; naturally enough, only if you agree. If that is the case, could you kindly fill in the attached form and post it back
Letters to me? We shall greatly appreciate it. Thank you for your time and consideration. I look forward to your reply. \closing{Yours Faithfully,} \ps{P.S. You can find the full text of GFDL license at \url{http://www.gnu.org/copyleft/fdl.html}.} \encl{Copyright permission form} \end{letter} \end{document} The output is generated via $ pdflatex koma_env
339
A sample letter with folding marks ready for standardized windowed envelopes.
Folding the print of the resulting file koma_env.pdf according the folding marks it can be placed into standardized windowed envelopes DIN C6/5, DL, C4, C5 or C6. In addition to the default, the KOMA-package includes predefined format definitions for different standardized Swiss and Japanese letter formats.
Letters
340
command \name{} \signature{} \address{} \location{} \telephone{} \makelabels \stopbreaks \startbreaks \opening{} \closing{} \cc{} \encl{} \ps \stopletter \returnaddress \startlabels \mlabel{}{} \descriptionlabel{} \ccname \enclname \pagename \headtoname \today "cc" "encl" "Page" "To" Long form date
description
Start a parbox introduced with \ccname: Start a parbox introduced with \enclname: Begins a new paragraph, normally at the close of the letter (empty) (empty)
Letters
341
Sources
KOMA-Script - The Guide [3]
References
[1] http:/ / mirror. hmc. edu/ ctan/ macros/ latex/ contrib/ envlab/ elguide. pdf [2] http:/ / bugs. debian. org/ cgi-bin/ bugreport. cgi?bug=547978 [3] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ koma-script/ scrguien. pdf
Presentations
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Presentations
342 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] LaTeX can be used for creating presentations. There are several packages for the task, including the beamer package.
Presentations
343
Introductory example
The beamer package is loaded by calling the beamer class: \documentclass{beamer} The usual header information may then be specified. Note that if you are compiling with XeTeX then you should use \documentclass[xetex,mathserif,serif]{beamer} Inside the usual document environment, multiple frame environments specify the content to be put on each slide. The frametitle command specifies the title for each slide (see image): \begin{document} \begin{frame} \frametitle{This is the first slide} %Content goes here \end{frame} \begin{frame} \frametitle{This is the second slide} \framesubtitle{A bit more information about this} %More content goes here \end{frame} % etc \end{document}
Presentations
344
The usual environments (itemize, enumerate, equation, etc.) may be used. Inside frames, you can use environments like block, theorem, proof, ... Also, \maketitle is possible to create the frontpage, if title and author are set. Trick: Instead of using \begin{frame}...\end{frame} , you can also use \frame{...} . For the actual talk, if you can compile it with pdflatex then you could use a pdf reader with a fullscreen mode, such as Adobe Reader. If you want to navigate in your presentation, you can use the almost invisible links in the bottom right corner without leaving the fullscreen mode.
Document Structure
Title page and information You give information about authors, titles and dates in the preamble \title[Crisis] % (optional, only for long titles) {The Economics of Financial Crisis} \subtitle{Evidence from India} \author[Author, Anders] % (optional, for multiple authors) {F.~Author\inst{1} \and S.~Anders\inst{2}} \institute[Universitten Hier und Dort] % (optional) { \inst{1}% Institut fr Informatik\\ Universitt Hier \and \inst{2}% Institut fr theoretische Philosophie\\ Universitt Dort } \date[KPT 2004] % (optional)
Presentations {Konferenz ber Prsentationstechniken, 2004} \subject{Informatik} In the document, you add the title page : \frame{\titlepage} Table of Contents The table of contents, with the current section highlighted, is displayed by: \begin{frame} \frametitle{Table of Contents} \tableofcontents[currentsection] \end{frame} This can be done automatically at the beginning of each section using the following code in the preamble: \AtBeginSection[] { \begin{frame} \frametitle{Table of Contents} \tableofcontents[currentsection] \end{frame} } Or for subsections: \AtBeginSubsection[] { \begin{frame} \frametitle{Table of Contents} \tableofcontents[currentsection,currentsubsection] \end{frame} } References (Beamer) Beamer does not officially support BibTeX. Instead bibliography items will need to be partly set "by hand" (see beameruserguide.pdf 3.20 [4]). The following example shows a references slide containing two entries: \begin{frame}[allowframebreaks] \frametitle<presentation>{Weiterfhrende Literatur} \begin{thebibliography}{10} \beamertemplatebookbibitems \bibitem{Autor1990} A.~Autor. \newblock {\em Einfhrung in das Prsentationswesen}. \newblock Klein-Verlag, 1990. \beamertemplatearticlebibitems \bibitem{Jemand2000} S.~Jemand. \newblock On this and that.
345
Presentations \newblock {\em Journal of This and That}, 2(1):50--100, 2000. \end{thebibliography} \end{frame} As the reference list grows, the reference slide will divide into two and so on, through use of the allowframebreaks option. Individual items can be cited after adding an 'optional' label to the relevant bibitem stanza. The citation call is simply \cite . Beamer also supports limited customization of the way references are presented (see the manual). Those who wish to use natbib [5], for example, with Beamer may need to troubleshoot both their document setup and the relevant BibTeX style file.
346
Style
Themes The first solution is to use a built-in theme such as Warsaw, Berlin, etc. The second solution is to specify colors, inner themes and outer themes. The Built-in solution To the preamble you can add the following line: \usetheme{Warsaw} to use the "Warsaw" theme. Beamer has several themes, many of which are named after cities (e.g. Barcelona, Madrid, Berlin, etc.). This Theme Matrix [6] contains the various theme and color combinations included with beamer. For more customizing options, have a look to the official documentation included in your distribution of beamer, particularly the part Change the way it looks. The full list of themes is:
Antibes Bergen Berkeley Berlin Copenhagen Darmstadt Dresden Frankfurt Goettingen Hannover Ilmenau JuanLesPins Luebeck Madrid Malmoe Marburg Montpellier PaloAlto Pittsburgh Rochester Singapore Szeged Warsaw boxes default
Color themes, typically with animal names, can be specified with \usecolortheme{beaver} The full list of color themes is:
default albatross beaver beetle crane dolphin dove fly lily orchid rose seagull seahorse whale wolverine
Presentations The do it yourself solution First you can specify the outertheme. The outertheme defines the head and the footline of each slide. \useoutertheme{infolines} Here is a list of all available outer themes: infolines miniframes shadow sidebar smoothbars smoothtree split tree
347
Then you can add the innertheme: \useinnertheme{rectangles} Here is a list of all available inner themes: rectangles circles inmargin rounded
You can define the color of every element: \setbeamercolor{alerted text}{fg=orange} \setbeamercolor{background canvas}{bg=white} \setbeamercolor{block body alerted}{bg=normal text.bg!90!black} \setbeamercolor{block body}{bg=normal text.bg!90!black} \setbeamercolor{block body example}{bg=normal text.bg!90!black} \setbeamercolor{block title alerted}{use={normal text,alerted text},fg=alerted text.fg!75!normal text.fg,bg=normal text.bg!75!black} \setbeamercolor{block title}{bg=blue} \setbeamercolor{block title example}{use={normal text,example text},fg=example text.fg!75!normal text.fg,bg=normal text.bg!75!black} \setbeamercolor{fine separation line}{} \setbeamercolor{frametitle}{fg=brown} \setbeamercolor{item projected}{fg=black} \setbeamercolor{normal text}{bg=black,fg=yellow} \setbeamercolor{palette sidebar primary}{use=normal text,fg=normal text.fg} \setbeamercolor{palette sidebar quaternary}{use=structure,fg=structure.fg} \setbeamercolor{palette sidebar secondary}{use=structure,fg=structure.fg} \setbeamercolor{palette sidebar tertiary}{use=normal text,fg=normal text.fg} \setbeamercolor{section in sidebar}{fg=brown} \setbeamercolor{section in sidebar shaded}{fg= grey}
Presentations \setbeamercolor{separation line}{} \setbeamercolor{sidebar}{bg=red} \setbeamercolor{sidebar}{parent=palette primary} \setbeamercolor{structure}{bg=black, fg=green} \setbeamercolor{subsection in sidebar}{fg=brown} \setbeamercolor{subsection in sidebar shaded}{fg= grey} \setbeamercolor{title}{fg=brown} \setbeamercolor{titlelike}{fg=brown} Colors can be defined as usual: \definecolor{chocolate}{RGB}{33,33,33} Block styles can also be defined: \setbeamertemplate{blocks}[rounded][shadow=true] \setbeamertemplate{background canvas}[vertical shading][bottom=white,top=structure.fg!25] \setbeamertemplate{sidebar canvas left}[horizontal shading][left=white!40!black,right=black] You can also suppress the navigation bar: \beamertemplatenavigationsymbolsempty Fonts You may also change the fonts for particular elements. If you wanted the title of the presentation as rendered by \frame{\titlepage} to occur in a serif font instead of the default sanserif, you would use: \setbeamerfont{title}{family=\rm} You could take this a step further if you are using OpenType fonts with Xe(La)TeX and specify a serif font with increased size and oldstyle proportional alternate number glyphs: \setbeamerfont{title}{family=\rm\addfontfeatures{Scale=1.18, Numbers={Lining, Proportional}}} Math Fonts The default settings for beamer use a different set of math fonts than one would expect from creating a simple math article. One quick fix for this is to use at the beginning of the file the option mathserif \documentclass[mathserif]{beamer} Others have proposed to use the command \usefonttheme[onlymath]{serif} but it is not clear if this works for absolutely every math character.
348
Presentations
349
Frames Options
The plain option. Sometimes you need to include a large figure or a large table and you don't want to have the bottom and the top of the slides. In that case, use the plain option : \frame[plain]{ % ... } If you want to include lots of text on a slide, use the shrink option. \frame[shrink]{ % ... } Before using any verbatim environment (like listings), you should pass the option fragile to the frame environement, as verbatim environments need to be typeset differently. Usually, the form fragile=singleslide is usable (for details see the manual). Note that the fragile option may not be used with \frame commands since it expects to encounter a \end{frame} , which should be alone on a single line. \begin{frame}[fragile] \frametitle{Source code} \begin{lstlisting}[caption=First C example] int main() { printf("Hello World!"); return 0; } \end{lstlisting} \end{frame}
Hyperlink navigation
Internal and external hyperlinks can be used in beamer to assist navigation. Clean looking buttons can also be added.
Animations
The following is merely an introduction to the possibilities in beamer. Chapter 8 of the beamer manual provides much more detail, on many more features. Making items appear on a slide is possible by simply using the \pause statement: \begin{frame} \frametitle{Some background} We start our discussion with some concepts. \pause The first concept we introduce originates with Erd\H os. \end{frame} Text or figures after \pause will display after one of the following events (which may vary between PDF viewers): pressing space, return or page down on the keyboard, or using the mouse to scroll down or click the next slide button. Pause can be used within \itemize etc.
Presentations Text animations For text animations, for example in the itemize environment, it is possible to specify appearance and disappearance of text by using <a-b> where a and b are the numbers of the events the item is to be displayed for (inclusive). For example: \begin{itemize} \item This one is always shown \item<1-> The first time (i.e. as soon as the slide loads) \item<2-> The second time \item<1-> Also the first time \only<1-1> This one is shown at the first time, but it will hide soon (on the next event after the slide loads). \end{itemize} A simpler approach for revealing one item per click is to use \begin{itemize}[<+->] . \begin{frame} \frametitle{`Hidden higher-order concepts?'} \begin{itemize}[<+->] \item The truths of arithmetic which are independent of PA in some sense themselves `{contain} essentially {\color{blue}{hidden higher-order}}, or infinitary, concepts'??? \item `Truths in the language of arithmetic which \ldots \item That suggests stronger version of Isaacson's thesis. \end{itemize} \end{frame} In all these cases, pressing page up, scrolling up, or clicking the previous slide button in the navigation bar will backtrack through the sequence.
350
Handout mode
In beamer class, the default mode is presentation which makes the slides. However, you can work in a different mode that is called handout by setting this option when calling the class: \documentclass[12pt,handout]{beamer} This mode is useful to see each slide only one time with all its stuff on it, making any \itemize[<+->] environments visible all at once (for instance, printable version). Nevertheless, this makes an issue when working with the only command, because its purpose is to have only some text or figures at a time and not all of them together. If you want to solve this, you can add a statement to precise the behavior it must have when dealing with only commands in handout mode. Suppose you have a code like this \only<1>{\includegraphics{pic1.eps}} \only<2>{\includegraphics{pic2.eps}} These pictures being completely different, you want them both in the handout, but they cannot be both on the same slide since they are large. The solution is to add the handout statement to have the following:
Presentations \only<1| handout:1>{\includegraphics{pic1.eps}} \only<2| handout:2>{\includegraphics{pic2.eps}} This will ensure the handout will make a slide for each picture. Now imagine you still have your two pictures with the only statements, but the second one show the first one plus some other graphs and you don't need the first one to appear in the handout. You can thus precise the handout mode not to include some only commands by: \only<1| handout:0>{\includegraphics{pic1.eps}} \only<2>{\includegraphics{pic2.eps}} The command can also be used to hide frames, e.g. \begin{frame}<handout:0> or even, if you have written a frame that you don't want anymore but maybe you will need it later, you can write \begin{frame}<0| handout:0> and this will hide your slide in both modes. (The order matters. Don't put handout:0|beamer:0 or it won't work.) A last word about the handout mode is about the notes. Actually, the full syntax for a frame is \begin{frame} ... \end{frame} \note{...} \note{...} ... and you can write your notes about a frame in the field note (many of them if needed). Using this, you can add an option to the class calling, either \documentclass[12pt,handout,notes=only]{beamer} or \documentclass[12pt,handout,notes=show]{beamer} The first one is useful when you make a presentation to have only the notes you need, while the second one could be given to those who have followed your presentation or those who missed it, for them to have both the slides with what you said. Note that the 'handout' option in the \documentclass line suppress all the animations. Important: the notes=only mode is literally doing only the notes. This means there will be no output file but the DVI. Thus it requires you to have run the compilation in another mode before. If you use separate files for a better distinction between the modes, you may need to copy the .aux file from the handout compilation with the slides (w/o the notes).
351
Presentations
352
Presentations Blocks Enclosing text in the block environment creates a distinct, headed block of text (a blank heading can be used). This allows to visually distinguish parts of a slide easily. There are three basic types of block. Their formatting depends on the theme being used. Simple \begin{frame} \begin{block}{This is a Block} This is important information \end{block} \begin{alertblock}{This is an Alert block} This is an important alert \end{alertblock} \begin{exampleblock}{This is an Example block} This is an example \end{exampleblock} \end{frame}
353
PDF options
You can specify the default options of your PDF.[7] \hypersetup{pdfstartview={Fit}} % fits the presentation to the window when first displayed
Presentations
354
References
[1] [2] [3] [4] [5] [6] [7] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ beamer/ http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ beamer/ doc/ beameruserguide. pdf Andrew Mertz and William Slough Beamer by Example http:/ / www. tex. ac. uk/ tex-archive/ macros/ latex/ contrib/ beamer/ doc/ beameruserguide. pdf http:/ / www. ctan. org/ pkg/ natbib/ http:/ / www. hartwork. org/ beamer-theme-matrix/ Other possible values are defined in the hyperref manual (http:/ / mirror. switch. ch/ ftp/ mirror/ tex/ macros/ latex/ contrib/ hyperref/ doc/ manual. html#TBL-7-40-1) [8] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ powerdot/ [9] http:/ / mirrors. ctan. org/ macros/ latex/ contrib/ powerdot/ docs/ powerdot. pdf
Links
Wikipedia:Beamer (LaTeX) Beamer user guide (http://www.ctan.org/tex-archive/macros/latex/contrib/beamer/doc/beameruserguide. pdf) (pdf) from CTAN The powerdot class (http://www.ctan.org/get/macros/latex/contrib/powerdot/doc/powerdot.pdf) (pdf) from CTAN A tutorial for creating presentations using beamer (http://www.math-linux.com/spip.php?article77)
Teacher's Corner
LaTeX
Teacher's Corner
355 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Teacher's Corner
356 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
Teacher's Corner
357
Intro
LaTeX has specific features for teachers. We present the exam class[1] which is useful for designing exams and exercises with solutions. Interested people could also have a look at the probsoln package[2] or the mathexm document class[3].
Preamble
In the preamble you can specify the following lines : \documentclass[a4paper,11pt]{exam} \printanswers % If you want to print answers % \noprintanswers % If you don't want to print answers \addpoints % if you want to count the points % \noaddpoints % if you don't want to count the points % Specifies the way question are displayed: \qformat{\textbf{Question\thequestion}\quad(\thepoints)\hfill} \usepackage{color} % defines a new color \definecolor{SolutionColor}{rgb}{0.8,0.9,1} % light blue \shadedsolutions % defines the style of the solution environment % \framedsolutions % defines the style of the solution environment % Defines the title of the solution environment: \renewcommand{\solutiontitle}{\noindent\textbf{Solution:}\par\noindent} You can replace the 3 first lines with the following : \documentclass[a4paper,11pt,answers,addpoints]{exam}
Document
The exam is included in the questions environment. The command \question introduces a new question. The number of points is specified in squared brackets. The solution is given in the solution environment. It appears only if \printanswers or answers as an option of the \documentclass are specified in the preamble.
Here is an example : \begin{questions} % Begins the questions environment \question[2] What is the solution? % Introduces a new question which is worth 2 points \begin{solution} Here is the solution \end{solution} \question[5] What is your opinion? \begin{solution} This is my opinion \end{solution} \end{questions}
Teacher's Corner It is also possible to add stuff only if answers are printed using the \ifprintanswers command. \ifprintanswers Only if answers are printed \else Only if answers are not printed \fi
358
Introduction
The macro \numquestions gives the total number of questions. The macro \numpoints gives the total number of points. \begin{minipage}{.8\textwidth} This exam includes \numquestions\ questions. The total number of points is \numpoints. \end{minipage} The backslash after \numquestion prevents the macro from gobbling the following whitespace as it normally would.
References
[1] examdoc (http:/ / www-math. mit. edu/ ~psh/ exam/ examdoc. pdf) Using the exam document class [2] Probsoln (http:/ / www. tex. ac. uk/ tex-archive/ macros/ latex/ contrib/ probsoln/ probsoln. pdf) creating problem sheets optionally with solutions [3] http:/ / mat140. bham. ac. uk/ ~richard/ programming/ tex/ exams/ msexdoc. pdf
Curriculum Vitae
LaTeX
Curriculum Vitae
359 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Curriculum Vitae
360 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] A curriculum vit or rsum has a universal requirement: its formatting must be flawless. This is a great example of cases where the power of LaTeX comes to the front. Thanks to its strong typographical stance, LaTeX is definitely a document processor of choice to write a CV. Of course you can design you own CV by hand. Otherwise, you may want to use a dedicated for that task. This way, writing a CV in LaTeX is as simple as filling the forms, and you are done. LaTeX will take care of the formatting brilliantly.
361
moderncv
From CTAN: Moderncv provides a documentclass for typesetting modern curriculums vitae, both in a classic and in a casual style. It is fairly customizable, allowing you to define your own style by changing the colours, the fonts, etc. The official package provides some well commented templates which may be a good start. You can find those templates in your distribution (if documentation is installed along packages) or ultimately on CTAN [2]. We will not repeat the templates here, so we will only provide a crash course. You should really have a look at the templates for more details.
First document
Most commands are self-explanatory. \documentclass[11pt,a4paper,sans]{moderncv} %% ModernCV themes \moderncvstyle{casual} \moderncvcolor{blue} \renewcommand{\familydefault}{\sfdefault} \nopagenumbers{} %% Character encoding \usepackage[utf8]{inputenc} %% Adjust the page margins \usepackage[scale=0.75]{geometry} %% Personal data \firstname{John} \familyname{Doe} \title{Resum title (optional)} \address{street and number}{postcode city} \mobile{+1~(234)~567~890} \phone{+2~(345)~678~901} \fax{+3~(456)~789~012} \email{john@doe.org} \homepage{www.johndoe.com} \extrainfo{additional information} \photo[64pt][0.4pt]{picture} \quote{Some quote (optional)} %%-----------------------------------------------------------------------------%% Content %%-----------------------------------------------------------------------------\begin{document} \makecvtitle \section{Education} \cventry{year--year}{Degree}{Institution}{City}{ \textit{Grade} }{Description} % arguments 3 to 6 can be left empty \cvitem{title}{ \emph{Title} } \cvitemwithcomment{Language 1}{Skill level}{Comment} \cvdoubleitem{category X}{XXX, YYY, ZZZ}{category Y}{XXX, YYY, ZZZ} \cvlistitem{Item 1} \cvlistdoubleitem{Item 2}{Item 3} %% ... \bibliography{publications} \end{document}
Curriculum Vitae
362
Multilingual support
It is especially convenient for rsums to have only one document for several output languages, since many parts are shared among versions (personal data, structure, etc.). LaTeX with appropriate macros provide a comfortable way to manage it. See Internationalization.
References
[1] http:/ / www. ctan. org/ topic/ cv [2] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ moderncv/ examples
363
Creating Graphics
Introducing Procedural Graphics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
364 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] In the Importing Graphics chapter, you learned that you can import or link graphics into LaTeX, such as graphics that you have created in another program or obtained elsewhere. In this chapter, you will learn how to create or embed graphics directly in a LaTeX document. The graphics is marked up using commands similar to those for typesetting bold text or creating mathematical formulas, as the following example of embedded graphics shows:
365
There are several packages supporting the creation of graphics directly in LaTeX, including picture, xy-Pic and PGF/TikZ, described in the following sections. Compared to WYSIWIG tools like Xfig or Inkscape, this approach is more time consuming, but leads to much better results. Furthermore, the ouput is flawlessly integrated to your document (no contrast in size nor fonts). See the Importing Graphics for more details on graphics importation and some attempts to circumvent to integration issue.
Overview
The picture environment allows programming pictures directly in LaTeX. On the one hand, there are rather severe constraints, as the slopes of line segments as well as the radii of circles are restricted to a narrow choice of values. On the other hand, the picture environment of LaTeX2e brings with it the \qbezier command, "q" meaning quadratic. Many frequently-used curves such as circles, ellipses, and catenaries can be satisfactorily approximated by quadratic Bzier curves, although this may require some mathematical toil. If a programming language like Java is used to generate \qbezier blocks of LaTeX input files, the picture environment becomes quite powerful. Although programming pictures directly in LaTeX is severely restricted, and often rather tiresome, there are still reasons for doing so. The documents thus produced are "small" with respect to bytes, and there are no additional graphics files to be dragged along. Packages like epic, eepic or pstricks enhance the original picture environment, and greatly strengthen the graphical power of LaTeX. While the former two packages just enhance the picture environment, the pstricks package has its own drawing environment, pspicture. The power of pstricks stems from the fact that this package makes extensive use of PostScript possibilities. Unfortunately it has one big shortcoming: it doesn't work together with pdfLaTeX, as such to generate a PDF document form TeX source you have to go TeXDVIPDF; losing hyperlinks, metadata and microtypographic features of pdflatex. In addition, numerous packages have been written for specific purposes. One of them is XY-pic, described at the end of this chapter. A wide variety of these packages are described in detail in The LaTeX Graphics Companion (not to be confused with The LaTeX Companion). Perhaps the most powerful graphical tool related with LaTeX is MetaPost, the twin of Donald E. Knuths METAFONT. MetaPost has the very powerful and mathematically sophisticated programming language of METAFONT. Contrary to METAFONT, which generates bitmaps, MetaPost generates encapsulated PostScript files, which can be imported in LaTeX. For an introduction, see A Users Manual for MetaPost. A very thorough discussion of LaTeX and TEX strategies for graphics (and fonts) can be found in TEX Unbound. The last but certainly not least is the PGF/TikZ system. While the previous systems (picture, epic, pstricks or metapost) focus on the how to draw, TikZ focuses more on the what to draw. One could say that TikZ is to drawing in LaTeX as LaTeX is to digital typesetting. It's recommended to use it if your LaTeX distribution includes it. In many cases, especially for more advanced diagrams, it may be easier to draw the graphics using external vector graphics software, and then import the file into the document (see ../Importing Graphics). However most software does not support LaTeX fonts or mathematical notation, which can result in not suitable and inconsistent graphics. There are several solutions to this problem.
MetaPost
366
MetaPost
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
MetaPost
367 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
Picture
368
Picture
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Picture
369 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] The picture environment allows programming pictures directly in LaTeX. On the one hand, there are rather severe constraints, as the slopes of line segments as well as the radii of circles are restricted to a narrow choice of values. On the other hand, the picture environment of LaTeX2e brings with it the \qbezier command, "q" meaning quadratic. Many frequently-used curves such as circles, ellipses, and catenaries can be satisfactorily approximated by quadratic Bzier curves, although this may require some mathematical toil. If a programming language like Java is used to generate \qbezier blocks of LaTeX input files, the picture environment becomes quite powerful.
Picture Although programming pictures directly in LaTeX is severely restricted, and often rather tiresome, there are still reasons for doing so. The documents thus produced are "small" with respect to bytes, and there are no additional graphics files to be dragged along. Packages like epic, eepic or pstricks enhance the original picture environment, and greatly strengthen the graphical power of LaTeX.
370
Basic Commands
A picture environment is available in any LaTeX distribution, without the need of loading any external package. This environment is created with one of the two commands \begin{picture}(x, y) ... \end{picture} or \begin{picture}(x, y)(x0, y0) ... \end{picture} The numbers x, y, x0, y0 are numbers (lengths) in the units of \unitlength , which can be reset any time (but not within a picture environment) with a command such as \setlength{\unitlength}{1.2cm} The default value of \unitlength is 1pt. The first pair, rectangular space for the picture. The optional second pair, corner of the reserved rectangle. Most drawing commands have one of the two forms \put(x, y){object} or \multiput(x, y)(dx, dy){n}{object} Bzier curves are an exception. They are drawn with the command \qbezier(x1, y1)(x2, y2)(x3, y3) , affects the reservation, within the document, of , assigns arbitrary coordinates to the bottom left
Line Segments
Line segments are drawn with the command: \put(x, y){ \line(x1, y1){length} } The \line command has two arguments: 1. a direction vector, 2. a "length" (sort of: this argument is the vertical length in the case of a vertical line segment and in all other cases the horizontal distance of the line, rather than the length of the segment itself). The components of the direction vector are restricted to the integers (6, 5, ... , 5, 6) and they have to be coprime (no common divisor except 1). The figure below illustrates all 25 possible slope values in the first quadrant. The length is relative to \unitlength .
Picture
371
\setlength{\unitlength}{5cm} \begin{picture}(1,1) \put(0,0){\line(0,1){1}} \put(0,0){\line(1,0){1}} \put(0,0){\line(1,1){1}} \put(0,0){\line(1,2){.5}} \put(0,0){\line(1,3){.3333}} \put(0,0){\line(1,4){.25}} \put(0,0){\line(1,5){.2}} \put(0,0){\line(1,6){.1667}} \put(0,0){\line(2,1){1}} \put(0,0){\line(2,3){.6667}} \put(0,0){\line(2,5){.4}} \put(0,0){\line(3,1){1}} \put(0,0){\line(3,2){1}} \put(0,0){\line(3,4){.75}} \put(0,0){\line(3,5){.6}} \put(0,0){\line(4,1){1}} \put(0,0){\line(4,3){1}} \put(0,0){\line(4,5){.8}} \put(0,0){\line(5,1){1}} \put(0,0){\line(5,2){1}} \put(0,0){\line(5,3){1}} \put(0,0){\line(5,4){1}} \put(0,0){\line(5,6){.8333}} \put(0,0){\line(6,1){1}} \put(0,0){\line(6,5){1}} \end{picture}
Arrows
Arrows are drawn with the command \put(x, y){\vector(x1, y1){length}} For arrows, the components of the direction vector are even more narrowly restricted than for line segments, namely to the integers (4, 3, ... , 3, 4). Components also have to be coprime (no common divisor except 1). Notice the effect of the \thicklines command on the two arrows pointing to the upper left. \setlength{\unitlength}{0.75mm} \begin{picture}(60,40) \put(30,20){\vector(1,0){30}} \put(30,20){\vector(4,1){20}} \put(30,20){\vector(3,1){25}} \put(30,20){\vector(2,1){30}} \put(30,20){\vector(1,2){10}} \thicklines \put(30,20){\vector(-4,1){30}} \put(30,20){\vector(-1,4){5}} \thinlines \put(30,20){\vector(-1,-1){5}} \put(30,20){\vector(-1,-4){5}} \end{picture}
Circles
The command \put(x, y){\circle{diameter}} draws a circle with center (x, y) and diameter (not radius) specified by diameter. The picture environment only admits diameters up to approximately 14mm, and even below this limit, not all diameters are possible. The \circle* command produces disks (filled circles). As in the case of line segments, one may have to resort to additional packages, such as eepic, pstricks, or tikz.
Picture
372
\setlength{\unitlength}{1mm} \begin{picture}(60, 40) \put(20,30){\circle{1}} \put(20,30){\circle{2}} \put(20,30){\circle{4}} \put(20,30){\circle{8}} \put(20,30){\circle{16}} \put(20,30){\circle{32}} \put(40,30){\circle{1}} \put(40,30){\circle{2}} \put(40,30){\circle{3}} \put(40,30){\circle{4}} \put(40,30){\circle{5}} \put(40,30){\circle{6}} \put(40,30){\circle{7}} \put(40,30){\circle{8}} \put(40,30){\circle{9}} \put(40,30){\circle{10}} \put(40,30){\circle{11}} \put(40,30){\circle{12}} \put(40,30){\circle{13}} \put(40,30){\circle{14}} \put(15,10){\circle*{1}} \put(20,10){\circle*{2}} \put(25,10){\circle*{3}} \put(30,10){\circle*{4}} \put(35,10){\circle*{5}} \end{picture} There is another possibility within the picture environment. If one is not afraid of doing the necessary calculations (or leaving them to a program), arbitrary circles and ellipses can be patched together from quadratic Bzier curves. See Graphics in LaTeX2e for examples and Java source files.
Picture
373
Ovals
The command \put(x, y){\oval(w, h)} or \put(x, y){\oval(w, h)[position]} produces an oval centered at (x, y) and having width w and height h. The optional position arguments b, t, l, r refer to "top", "bottom", "left", "right", and can be combined, as the example illustrates. Line thickness can be controlled by two kinds of commands: \linethickness{''length''} on the one hand, \thinlines and \thicklines on the other. While \linethickness{''length''} applies only to horizontal and vertical lines (and quadratic Bzier curves), \thinlines and \thicklines apply to oblique line segments as well as to circles and ovals. \setlength{\unitlength}{0.75cm} \begin{picture}(6,4) \linethickness{0.075mm} \multiput(0,0)(1,0){7}% {\line(0,1){4}} \multiput(0,0)(0,1){5}% {\line(1,0){6}} \thicklines \put(2,3){\oval(3,1.8)} \thinlines \put(3,2){\oval(3,1.8)} \thicklines \put(2,1){\oval(3,1.8)[tl]} \put(4,1){\oval(3,1.8)[b]} \put(4,3){\oval(3,1.8)[r]} \put(3,1.5){\oval(1.8,0.4)} \end{picture}
Picture
374
\setlength{\unitlength}{0.5mm} \begin{picture}(120,168) \newsavebox{\foldera} \savebox{\foldera} (40,32)[bl]{% definition \multiput(0,0)(0,28){2} {\line(1,0){40}} \multiput(0,0)(40,0){2} {\line(0,1){28}} \put(1,28){\oval(2,2)[tl]} \put(1,29){\line(1,0){5}} \put(9,29){\oval(6,6)[tl]} \put(9,32){\line(1,0){8}} \put(17,29){\oval(6,6)[tr]} \put(20,29){\line(1,0){19}} \put(39,28){\oval(2,2)[tr]} } \newsavebox{\folderb} \savebox{\folderb} (40,32)[l]{% definition \put(0,14){\line(1,0){8}} \put(8,0){\usebox{\foldera}} } \put(34,26){\line(0,1){102}} \put(14,128){\usebox{\foldera}} \multiput(34,86)(0,-37){3} {\usebox{\folderb}} \end{picture}
denotes the intermediate control point. The respective tangent slopes, equations
See Graphics in LaTeX2e for a Java program which generates the necessary \qbezier command line. \setlength{\unitlength}{0.8cm} \begin{picture}(6,4) \linethickness{0.075mm} \multiput(0,0)(1,0){7} {\line(0,1){4}} \multiput(0,0)(0,1){5} {\line(1,0){6}} \thicklines \put(0.5,0.5){\line(1,5){0.5}} \put(1,3){\line(4,1){2}} \qbezier(0.5,0.5)(1,3)(3,3.5) \thinlines \put(2.5,2){\line(2,-1){3}} \put(5.5,0.5){\line(-1,5){0.5}} \linethickness{1mm} \qbezier(2.5,2)(5.5,0.5)(5,3) \thinlines \qbezier(4,2)(4,3)(3,3) \qbezier(3,3)(2,3)(2,2) \qbezier(2,2)(2,1)(3,1) \qbezier(3,1)(4,1)(4,2) \end{picture} As this example illustrates, splitting up a circle into 4 quadratic Bzier curves is not satisfactory. At least 8 are needed. The figure again shows the effect of the \linethickness command on horizontal or vertical lines, and of the \thinlines and the \thicklines commands on oblique line segments. It also shows that both kinds of commands affect quadratic Bzier curves, each command overriding all previous ones.
Picture
375
Catenary
\setlength{\unitlength}{1cm} \begin{picture}(4.3,3.6)(-2.5,-0.25) \put(-2,0){\vector(1,0){4.4}} \put(2.45,-.05){$x$} \put(0,0){\vector(0,1){3.2}} \put(0,3.35){\makebox(0,0){$y$}} \qbezier(0.0,0.0)(1.2384,0.0) (2.0,2.7622) \qbezier(0.0,0.0)(-1.2384,0.0) (-2.0,2.7622) \linethickness{.075mm} \multiput(-2,0)(1,0){5} {\line(0,1){3}} \multiput(-2,0)(0,1){4} {\line(1,0){4}} \linethickness{.2mm} \put( .3,.12763){\line(1,0){.4}} \put(.5,-.07237){\line(0,1){.4}} \put(-.7,.12763){\line(1,0){.4}} \put(-.5,-.07237){\line(0,1){.4}} \put(.8,.54308){\line(1,0){.4}} \put(1,.34308){\line(0,1){.4}} \put(-1.2,.54308){\line(1,0){.4}} \put(-1,.34308){\line(0,1){.4}} \put(1.3,1.35241){\line(1,0){.4}} \put(1.5,1.15241){\line(0,1){.4}} \put(-1.7,1.35241){\line(1,0){.4}} \put(-1.5,1.15241){\line(0,1){.4}} \put(-2.5,-0.25){\circle*{0.2}} \end{picture} In this figure, each symmetric half of the catenary is approximated by a quadratic Bzier curve.
The right half of the curve ends in the point (2, 2.7622), the slope there having the value m = 3.6269. Using again equation (*), we can calculate the intermediate control points. They turn out to be (1.2384, 0) and (1.2384, 0). The crosses indicate points of the real catenary. The error is barely noticeable, being less than one percent. This example points out the use of the optional argument of the \begin{picture} command. The picture is defined in convenient "mathematical" coordinates, whereas by the command \begin{picture}(4.3,3.6)(-2.5,-0.25) its lower left corner (marked by the black disk) is assigned the coordinates (2.5,0.25).
Plotting graphs
\setlength{\unitlength}{0.8cm} \begin{picture}(6,4)(-3,-2) \put(-2.5,0){\vector(1,0){5}} \put(2.7,-0.1){$\chi$} \put(0,-1.5){\vector(0,1){3}} \multiput(-2.5,1)(0.4,0){13} {\line(1,0){0.2}} \multiput(-2.5,-1)(0.4,0){13} {\line(1,0){0.2}} \put(0.2,1.4) {$\beta=v/c=\tanh\chi$} \qbezier(0,0)(0.8853,0.8853) (2,0.9640) \qbezier(0,0)(-0.8853,-0.8853) (-2,-0.9640) \put(-3,-2){\circle*{0.2}} \end{picture} The control points of the two Bzier curves were calculated with formulas (*). The positive branch is determined by , and , . Again, the picture is defined in mathematically convenient coordinates, and the lower left corner is assigned the mathematical coordinates (3,2) (black disk).
Picture
376
PGF/TikZ
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
PGF/TikZ
377 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
PGF/TikZ
378
One possible solution how to draw graphics directly with TeX commands is PGF/TikZ. TikZ can produce portable graphics in both PDF and PostScript formats using either plain (pdf)TEX, (pdf)Latex or ConTEXt. It comes with very good documentation [1] and an extensive collection of examples: http:/ / www. texample.net/tikz/ PGF ("portable graphics format") is the basic layer, providing a set of basic commands for producing graphics, and TikZ ("TikZ ist kein Zeichenprogramm") is the frontend layer with a special syntax, making the use of PGF easier. TikZ commands are prevalently similar to Metafont, the option mechanism is similar to PsTricks syntax.
Example of graphics done with Tikz. Note the slightly translucent top layer.
While the previous systems (picture, epic, pstricks or metapost) focus on the how to draw, TikZ focuses more on the what to draw. One could say that TikZ is to drawing in LaTeX as LaTeX is to digital typesetting. It's recommended to use it if your LaTeX distribution includes it. Other packages building on top of TikZ (e.g., for drawing electrical circuits) can be found here: http:/ / ftp. dante. de/ tex-archive/help/Catalogue/bytopic.html#pgftikzsection In the following some basics of TikZ are presented.
PGF/TikZ scale=factor or different for height and width, e.g: xscale=2.5, yscale=0.5
379
Specifying Coordinates
Coordinates are specified in round brackets in an arbitrary TEX dimension either using cartesian coordinates (comma separated), e.g. 1cm in the x direction and 2pt in the y direction (1cm,2pt)
or using polar coordinates (colon separated), e.g. 1cm in 30 degree direction (30:1cm)
Without specifying a unit (1,2), the standard one is cm (1cm,2cm). Relative coordinates to the previous given point are given by adding one or two plus signs in front of the coordinate. With "++" the last point of the path becomes the current position, with "+" the previous point stays the current path position. Example: 2 standard units to the right of the last point used: ++(2,0)
PGF/TikZ join=<type: round, bevel, or miter>". Line pattern options: "dash pattern=<dash pattern>" (e.g. "dash pattern=on 2pt off 3pt on 4pt off 4pt"), "dash phase=dash phase", "solid", "dashed", "dotted", "dashdotted", "densely dotted", "loosely dotted", "double". Options for filling color=<color>" paths are e.g. "fill=<fill color>", "pattern=<name>", "pattern
380
Straight lines are given by coordinates separated by a double minus, \draw (1,0) -- (0,0) -- (0,1); The first coordinate represents a move-to operation. This is followed by a series of path extension operations, like "-- (coordinates)". The same path with some drawing options: \draw[red, dashed, very thick, rotate=30] (1,0) -- (0,0) -- (0,1); A connected path can be closed using the "--cycle" operation: \draw (1,0) -- (0,0) -- (0,1) -- cycle; A further move-to operation in an existing path starts a new part of the path, which is not connected to the previous part of the path. Here: Move to (0,0) straight line to (2,0), move to (0,1) straight line to (2,1): \draw (0,0) -- (2,0) (0,1) -- (2,1); Connecting two points via straight lines that are only horizontal and vertical, use for first horizontal then vertial \draw (0,0) -| (1,1); or for first vertical then horizontal \draw (0,0) |- (1,1); Curved paths using a Bezier curve can be created using the "..controls() ..()" command, with one or two control points. \draw (0,0) .. controls (1,1) .. (4,0) (5,0) .. controls (6,0) and (6,1) .. (5,2); User-defined paths can be created using the "to" operation. Without an option it corresponds to a straight line, exactly like the double minus command. Using the "out" and "in" option a curved path can created. E.g. "[out=135,in=45]" causes the path to leave at an angle of 135 degree at the first coordinate and arrive at an angle of 45 degree at the second coordinate. \draw (0,0) to (3,2); \draw (0,0) to[out=90,in=180] (3,2); \draw (0,0) to[bend right] (3,2); For rectangles a special syntax exist. Use a move-to operation to one corner and after "rectangle" the coordinates of the diagonal corner. The last one becomes the new current point. \draw (0,0) rectangle (1,1); \shade[top color=yellow, bottom color=black] (0,0) rectangle (2,-1); \filldraw[fill=green!20!white, draw=green!40!black] (0,0) rectangle (2,1);
PGF/TikZ The fill color "green!20!white" means 20% green and 80% white mixed together. Circles and ellipses paths are defined beginning with their center then using the "circle command" either with one length as radius of a circle or with two lengths as semi-axes of an ellipse. \draw (0,0) circle [radius=1.5]; \draw (0,0) circle (2cm); % old syntax \draw (0,0) circle [x radius=1.5cm, y radius=10mm]; \draw (0,0) circle (1.2cm and 8mm); % old syntax \draw (0,0) circle [x radius=1cm, y radius=5mm, rotate=30]; \draw[rotate=30] (0,0) ellipse (20pt and 10pt); % old syntax The command "arc" creates a part of a circle or an ellipse: \draw (0,0) arc (0:270:8mm); \draw (0,0) arc (0:315:1.75cm and 1cm); \filldraw[fill=cyan, draw=blue] (0,0) -- (12mm,0mm) arc (0:30:12mm) -(0,0); Or in an alternative syntax: \draw (0,0) arc[radius = 8mm, start angle= 0, end angle= 270] \draw (0,0) arc[x radius = 1.75cm, y radius = 1cm, start angle= 0, end angle= 315] There are many more predefined commands for special paths, like "grid", "parabola", "sin", "cos" (sine or cosine curve in the interval [0,/2]). \draw[help lines] (0,0) grid (2,3); \draw[step=0.5, gray, very thin] (-1.4,-1.4) grid (1.4,1.4); \draw (0,0) parabola (1,1.5) parabola[bend at end] (2,0); \draw (0,0) sin (1,1) cos (2,0) sin (3,-1) cos (4,0) sin (5,1); The option "help lines" denotes "fine gray". To add arrow tips there are simple options for the drawing command: \draw [->] (0,0) -- (30:20pt); \draw [<->] (1,0) arc (180:30:10pt); \draw [<<->] (2,0) -- ++(0.5,10pt) -- ++(0.5,-10pt) -- ++(0.5,10pt); A loop can be realized by "\foreach variable in {list of values} commands". \foreach \x in {0,...,9} \draw (\x,0) circle (0.4); PGF also has a math engine which enables you to plot functions: \draw [domain=<xmin>:<xmax>] plot (\x, {function}); Many functions are possible, here a selection: factorial(\x), sqrt(\x), pow(\x,y), exp(\x), ln(\x), log10(\x), log2(\x), abs(\x), mod(\x,y), round(\x), floor(\x), ceil(\x), sin(\x), cos(\x), tan(x), min(\x,y,), max(\x,y). The trigonometric functions assume that x is in degrees; if x is expressed in radians use e.g. sin(\x r). Two constants can be useful: e, which is equal to 2.718281828, and pi, which is equal to 3.141592654. An example with two functions:
381
PGF/TikZ \draw \draw \draw \draw \draw [help lines] (-2,0) grid (2,4); [->] (-2.2,0) -- (2.2,0); [->] (0,0) -- (0,4.2); [green, thick, domain=-2:2] plot (\x, {4-\x*\x}); [domain=-2:2, samples=50] plot (\x, {1+cos(pi*\x r});
382
Nodes
A node is typically a rectangle or circle or another simple shape with some text on it. In the simplest case, a node is just some text that is placed at some coordinate. Nodes are not part of the path itself, they are added to the picture after the path has been drawn. Inside a path operation use the following syntax after a given coordinate: node[<options>](<name>){<text>} The "(<name>)" is a name for later reference and it is optional. If you only want to name a certain position without writing text there are two possibilities: node[<options>](<name>){} coordinate[<options>](<name>) Writing text along a given path using the node command is shown as simple example: \draw[dotted] (0,0) node {1st node} -- (1,1) node {2nd node} -- (0,2) node {3rd node} -- cycle; Possible options for the node command are e.g. "inner sep=<dimension>", "outer sep=<dimension>", "minimum size=<dimension>", "shape aspect=<aspect ratio>", "text=<color>", "font=", "align=<left_right_center>". A node is centered at the current coordinate by default. Often it would be better to have the node to the besides the actual coordinate: Right ("right" or "anchor=west"), left ("left" or "anchor=east"), above ("above" or "anchor=south"), below ("below" or "anchor=north"). Combinations are also possible, like "anchor=north east" or "below left". \fill[fill=yellow] (0,0) node {1st node} -- (1,1) node[circle,inner sep=0pt,draw] {2nd node} -- (0,2) node[fill=red!20,draw,double,rounded corners] {3rd node}; To place nodes on a line or a curve use the "pos=<fraction>" option, where fraction is a floating point number between 0 representing the previous coordinate and 1 representing the current coordinate. \draw (0,0) -- (3,1) node[pos=0]{0} node[pos=0.5]{1/2} node[pos=0.9]{9/10}; There exist some abbreviations: "at start" for "pos=0", "very near start" for "pos=0.125", "near start" for "pos=0.25", "midway" for "pos=0.5", "near end" for "pos=0.75", "very near end" for "pos=0.875", "at end" for "pos=1". The "sloped" option causes the node to be rotated to become a tangent to the curve.
PGF/TikZ Since nodes are often the only path operation on paths, there are special commands for creating paths containing only a node, the first with text ouput, the secound without: \node[<options>](<name>) at (<coordinate>){<text>}; \coordinate[<options>](<name>) at (<coordinate>); One can connect nodes using the nodes' labels as coordinates. Having "\path(0,0) node(x) {} (3,1) node(y) {};" defined, the node at (0,0) got the name "(x)" and the one at (3,1) got a label "(y)". \path (0,0) node(x) {} (3,1) node(y) {}; \draw (x) -- (y); Equivalent to \coordinate (x) at (0,0); \coordinate (y) at (3,1); \draw (x) -- (y); Multiline text can be included inside a node. A new line is indicated by double backslash "\\", but additionally you have to specify the alignment using the node option "align=". Here an example: \filldraw (0,0) circle (2pt) node[align=left, below] {test 1\\is aligned left} -(4,0) circle (2pt) node[align=center, below] {test 2\\is centered} -(8,0) circle (2pt) node[align=right, below] {test 3\\is right aligned}; Path construction operations try to be clever, such that the path starts at the border of the node's shape and not from the node's center. \path (0,0) node(x) {Hello World!} (3,1) node[circle,draw](y) {$\int_1^2 x \mathrm d x$}; \draw[->,blue] (x) -- (y); \draw[->,red] (x) -| node[near start,below] {label} (y); \draw[->,orange] (x) .. controls +(up:1cm) and +(left:1cm) .. node[above,sloped] {label} (y); Once the node x has been defined, you can use anchors as defined above relative to (x) as "(x.<anchor>)", like "(x.north)".
383
Examples
Example 1 \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \draw[thick,rounded corners=8pt] (0,0) -- (0,2) -- (1,3.25) -- (2,2) -- (2,0) -- (0,2) -- (2,2) -- (0,0) -- (2,0);
PGF/TikZ \end{tikzpicture} \end{document} Example 2 \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture}[scale=3] \draw[step=.5cm, gray, very thin] (-1.2,-1.2) grid (1.2,1.2); \filldraw[fill=green!20,draw=green!50!black] (0,0) -- (3mm,0mm) arc (0:30:3mm) -- cycle; \draw[->] (-1.25,0) -- (1.25,0) coordinate (x axis); \draw[->] (0,-1.25) -- (0,1.25) coordinate (y axis); \draw (0,0) circle (1cm); \draw[very thick,red] (30:1cm) -- node[left,fill=white] {$\sin \alpha$} (30:1cm |- x axis); \draw[very thick,blue] (30:1cm |- x axis) -node[below=2pt,fill=white] {$\cos \alpha$} (0,0); \draw (0,0) -- (30:1cm); \foreach \x/\xtext in {-1, -0.5/-\frac{1}{2}, 1} \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north,fill=white] {$\xtext$}; \foreach \y/\ytext in {-1, -0.5/-\frac{1}{2}, 0.5/\frac{1}{2}, 1} \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east,fill=white] {$\ytext$}; \end{tikzpicture} \end{document} Example 3: A Torus \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \draw (-1,0) to[bend left] (1,0); \draw (-1.2,.1) to[bend right] (1.2,.1); \draw[rotate=0] (0,0) ellipse (100pt and 50pt); \end{tikzpicture} \end{document} Example 4: Some functions \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture}[domain=0:4] \draw[very thin,color=gray] (-0.1,-1.1) grid (3.9,3.9);
384
PGF/TikZ \draw[->] (-0.2,0) -- (4.2,0) node[right] {$x$}; \draw[->] (0,-1.2) -- (0,4.2) node[above] {$f(x)$}; \draw[color=red] plot (\x,\x) node[right] {$f(x) =x$}; \draw[color=blue] plot (\x,{sin(\x r)}) node[right] {$f(x) = \sin x$}; \draw[color=orange] plot (\x,{0.05*exp(\x)}) node[right] {$f(x) = \frac{1}{20} \mathrm e^x$}; \end{tikzpicture} \end{document}
385
References
[1] http:/ / www. ctan. org/ tex-archive/ graphics/ pgf/ base/ doc/ generic/ pgf/ pgfmanual. pdf
PSTricks
LaTeX
PSTricks
386 Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
PSTricks
387 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] PSTricks is a set of extensions. The base package is pstricks, other packages may be loaded when required. The xcolor extension gets loaded along PSTricks, so there is no need to load it manually. PSTricks has one technical specification: it uses PostScript internally, hence the name. Thus you cannot use the pdftex or pdflatex compilers, you will need to use dvips to get your proper document. It is still possible to get PDF from PS files thanks to ps2pdf. There is also the possibilit to use the PDFTricks extension, which makes it feasible to use pdflatex together with PSTricks commands.
PSTricks However, if you have installed the package xetex-pstricks, you can use pstricks with xetex or xelatex without modification of source file.
388
Fundamental objects
Lines and polylines
A simple line gets printed with \psline(x0,y0)(x1,y1) To get a vector, add an arrow as parameter: \psline{->}(x0,y0)(x1,y1) You can add as many point as you want to get a polyline: \psline(x0,y0)(x1,y1)(x2,y3)(xn,yn) To get rounded corners, add the following option: \psline[linearc=0.2,->](0,0)(0.5,0.5)(1,1)
Rectangles
\psframe(x0,y0)(x1,y1) \psframe*(x0,y0)(x1,y1) The starred version prints a filled rectangle. Use the following parameter to get rounded corners: \psframe[framearc=0.2](x0,y0)(x1,y1)
Polygons
Polygons are always closed. The syntax is the same as for \psline : \pspolygon(x0,y0)(x1,y1)(x2,y3)...(xn,yn)
PSTricks As for rectangles, the starred version prints a filled polygon. And the linearc=0.2 option will print rounded corners.
389
Curves
\psparabola(x0,y0)(x1,y1) will print a symetric parabola with vertical asymptote, vertex (x1,y1) and ending at (x0,y0). Use \psbezier to print a Bzier curve with an arbitrary number of control points. Arcs have at most 4 control points. Use the showpoints=true option to print the control points and the tangents. Use \pscurve to print the interpolation of the given points. The \psecurve command omits the first and the last arcs.
Text
Use \rput(x,y){text} to print text. Provide an angle to rotate the text. \rput{angle}(x,y){text} You can provide the anchor of the text which will be at the specified coordinate. \rput[t]{45}(5,5){text} Available anchors: B, Bl, Br: baseline center, left and right. t, tl, tr: top center, left and right. b, bl, br: bottom center, left and right. There is also the \uput command with further options: \uput{distance}[angle](x,y){text} The distance parameter is the distance from the coordinate. PSTricks features several frame style for text. \psframebox{text}: rectangle. \psdblframebox{text}: double rectangle. \psshadowbox{text}: shaded rectangle.
390
Example: \rput(5,5){\psdiabox*[fillcolor=green]{text}} Using the pst-text extension, it is possible to draw a text path. \pstextpath{shape}{text} To print a text following a path without printing the path, you need to use \psset{linestyle=none} . Example: \usepackage{pst-text} % ... \begin{pspicture}(5,5) \psset{linestyle=none} \pstextpath{\psline(0,0)(1,1)(2,0)}{triangle text} \end{pspicture}
Grids
Without any parameter, the \psgrid command will print a grid all over the pspicture, with a spacing of 0.2 (i.e. 2mm). You can specify parameters: \psgrid(xmax,ymax) : prints a grid from (0,0) to (xmax,ymax). \psgrid(xmin,ymin)(xmax,ymax) : prints a grid from (xmin,ymin) to (xmax,ymax). \psgrid(x0,y0)(xmin,ymin)(xmax,ymax) : prints a grid from (xmin,ymin) to (xmax,ymax), one of the node is at (x0,y0). griddots=value : the full line of the main graduations is replaced by a dotted line. The value is the number of dots per graduation. subgriddots=value : same as griddots but for sub-graduations. gridcolor=color,subgridcolor=color : color of graduations and sub-graduations. gridwidth=value,subgridwidth=value : width of the lines. subgriddiv=value : number of subgraduations between two main graduations. gridlabels=value : size of the label numbers. ticksize=value : self-explanatory. ticksize=valueneg valuepos : same as above, but valueneg specifies the size for negative coordinates, valuepos for positive coordinates. ticklinestyle=value : self-explanatory. value may be one of solid, dashed, dotted . This is useful for huge graduations (i.e.ticksize is high). Example \psgrid[griddots=5, subgriddiv=0, gridlabels=0pt](-1,-1)(5,5) Axis If you want to add axes, use the pstricks-add extension with the following commands:
PSTricks \psaxes(xmin,ymin)(xmax,ymax) \psaxes(x0,y0)(xmin,ymin)(xmax,ymax) (xmin,ymin) and (xmax,ymax) being the extreme, (x0,y0) being the intersection. Options Dx=value and Dy=value defines the spacing between graduations. comma lets you use the comma as decimal separator. As for lines, {->} adds arrows on axes. Example \usepackage{pstricks-add} % ... \begin{pspicture}(-1,-1)(5,5) \psaxes[comma,Dx=0.5,Dy=0.5]{->}(0,0)(3,3) \end{pspicture}
391
Generic parameters
All shapes
These are to be added between square brackets. linewidth=value linecolor=color linestyle=value doubleline=true showpoints=true : if value is without unit, then the default unit is used. : color is as defined by the xcolorpackage. : value is one of dashed,dotted . . : highlights points.
dotscale=value specifies the size of the points. dotstyle=value where value is among: *: disc o: circle +,x: cross square, squarre*: starred version is filled. diamond, diamond* triangle, triangle* etc.
For example \pscircle[linewidth=0.2,linestyle=dashed,linecolor=blue](0,0){1} To apply parameters globally: \psset{linewidth=0.2,linestyle=dashed,linecolor=blue} \pscircle(0,0){1} This command also lets you change the default unit for lengths. unit=value xunit=value and yunit=value value is a number with or without unit. This changes the scale of the drawings, but will not change the width of lines.
PSTricks
392
Open shapes
You can define the extreme of an open shape (line, polyline, arc, etc.) with an optional parameter {symbol1-symbol2} . There is a decent list of available symbols. < or >: arrow. << or >>: double arrow. |: bar. |*: centered bar. oo: circle. o: centered circle. **: disk. *: centered disk. |< or >|: arrow plus bar. cc: rounded extreme. c: centered rounded extreme.
Example: \psline{|->>}(x0,y0)(x1,y1)
Close shapes
For close shape you may define the fillstyle. fillstyle=value : pattern. Possible values: crosshatch, crosshatch*, vlines, vlines*, hlines, hlines*, solid . fillcolor=color . hatchcolor=color . hatchwidth=value . hatchsep=value . hatchangle=value . Example: \pscircle[hatchcolor=blue,fillstyle=vlines](0,0){1}
Object location
The \rput and \uput commands can be used to move any object. Example \begin{pspicture}(5,5) \psline{->}(0,0)(1,1) \rput(1,1){\psline{->}(0,0)(1,1)} \end{pspicture} or \begin{pspicture}(5,5) \psline{->}(0,0)(1,1) \psline{->}(1,1)(2,2) \end{pspicture} You can repeat the operation with \multirput :
PSTricks \multirput(x0,y0)(xoffset, yoffset){times}{object} You can use the same options as for \rput : \multirput[reference]{angle}(x0,y0)(xoffset, yoffset){times}{object} With no text but with graphics only, you can use the \multips command: \multips(x0,y0)(xoffset, yoffset){times}{object} \multips{angle}(x0,y0)(xoffset,yoffset){times}{object}
393
Xy-pic
394
Xy-pic
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Xy-pic
395 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] xy is a special package for drawing diagrams. To use it, simply add the following line to the preamble of your document: \usepackage[all]{xy} where "all" means you want to load a large standard set of functions from Xy-pic, suitable for developing the kind of diagrams discussed here.
Xy-pic The primary way to draw Xy-pic diagrams is over a matrix-oriented canvas, where each diagram element is placed in a matrix slot: \begin{displaymath} \xymatrix{A & B \\ C & D } \end{displaymath}
396
The \xymatrix command must be used in math mode. Here, we specified two lines and two columns. To make this matrix a diagram we just add directed arrows using the \ar command. \begin{displaymath} \xymatrix{ A \ar[r] & B \ar[d] \\ D \ar[u] & C \ar[l] } \end{displaymath}
The arrow command is placed on the origin cell for the arrow. The arguments are the direction the arrow should point to (up, down, right and left). \begin{displaymath} \xymatrix{ A \ar[d] \ar[dr] \ar[r] & B \\ D & C } \end{displaymath}
To make diagonals, just use more than one direction. In fact, you can repeat directions to make bigger arrows. \begin{displaymath} \xymatrix{ A \ar[d] \ar[dr] \ar[drr] & & \\ B & C & D } \end{displaymath}
We can draw even more interesting diagrams by adding labels to the arrows. To do this, we use the common superscript and subscript operators. \begin{displaymath} \xymatrix{ A \ar[r]^f \ar[d]_g & B \ar[d]^{g'} \\ D \ar[r]_{f'} & C } \end{displaymath}
As shown, you use these operators as in math mode. The only difference is that that superscript means "on top of the arrow", and subscript means "under the arrow". There is a third operator, the vertical bar: | It causes text to be placed in the arrow. \begin{displaymath} \xymatrix{ A \ar[r]
Xy-pic
397
To draw an arrow with a hole in it, use \ar[...]|\hole. In some situations, it is important to distinguish between different types of arrows. This can be done by putting labels on them, or changing their appearance \shorthandoff{"} \begin{displaymath} \xymatrix{ \bullet\ar@{->}[rr] && \bullet\\ \bullet\ar@{.<}[rr] && \bullet\\ \bullet\ar@{~)}[rr] && \bullet\\ \bullet\ar@{=(}[rr] && \bullet\\ \bullet\ar@{~/}[rr] && \bullet\\ \bullet\ar@{^{(}->}[rr] && \bullet\\ \bullet\ar@2{->}[rr] && \bullet\\ \bullet\ar@3{->}[rr] && \bullet\\ \bullet\ar@{=+}[rr] && \bullet } \end{displaymath} \shorthandon{"}
Notice the difference between the following two diagrams: \begin{displaymath} \xymatrix{ \bullet \ar[r] \ar@{.>}[r] & \bullet } \end{displaymath}
\begin{displaymath} \xymatrix{ \bullet \ar@/^/[r] \ar@/_/@{.>}[r] & \bullet } \end{displaymath} The modifiers between the slashes define how the curves are drawn. Xy-pic offers many ways to influence the drawing of curves; for more information, check the Xy-pic documentation. If you are interested in a more thorough introduction then consult the Xy-pic Home Page [1], which contains links to several other tutorials as well as the reference documentation.
References
[1] http:/ / xy-pic. sourceforge. net
Creating 3D graphics
398
Creating 3D graphics
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Creating 3D graphics
399 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] For creating three-dimensional graphics, there is basic functionality in the PGF/TikZ package, although drawing 3D graphics with PGF/TikZ is very non-flexible, mainly because it lacks functionality for identifying the surfaces that are covered by other surfaces and should be excluded from the rendered image. A package that can handle this correctly is the pst-solides3d [1] package. Another way to create 3D graphics is to use Asymptote
Creating 3D graphics
400
References
[1] http:/ / www. ctan. org/ pkg/ pst-solides3d
401
Programming
Macros
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Macros
402 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Documents produced with the commands you have learned up to this point will look acceptable to a large audience. While they are not fancy-looking, they obey all the established rules of good typesetting, which will make them easy to read and pleasant to look at. However, there are situations where LaTeX does not provide a command or environment that matches your needs, or the output produced by some existing command may not meet your requirements.
Macros In this chapter, I will try to give some hints on how to teach LaTeX new tricks and how to make it produce output that looks different from what is provided by default. LaTeX is a fairly high-level language compared to Plain TeX and thus is more limited. The next chapter will focus on Plain TeX and will explain advanced technics for programming.
403
New commands
To add your own commands, use the \newcommand{name}[num]{definition} command. Basically, the command requires two arguments: the name of the command you want to create, and the definition of the command. Note that the command name can but need not be enclosed in braces, as you like. The num argument in square brackets is optional and specifies the number of arguments the new command takes (up to 9 are possible). If missing it defaults to 0, i.e. no argument allowed. The following two examples should help you to get the idea. The first example defines a new command called \wbal that will print "The Wikibook about LaTeX". Such a command could come in handy if you had to write the title of this book over and over again. \newcommand{\wbal}{The Wikibook about \LaTeX} This is \wbal'' \ldots{} \wbal''
This is The Wikibook about LaTeX The Wikibook about LaTeX
The next example illustrates how to define a new command that takes one argument. The #1 tag gets replaced by the argument you specify. If you wanted to use more than one argument, use #2 and so on, these arguments are added in an extra set of brackets. \newcommand{\wbalsup}[1] { This is the Wikibook about LaTeX supported by #1} \newcommand{\wbalTwo}[2] { This is the Wikibook about LaTeX supported by #1 #2} % in the document body: \begin{itemize} \item \wbalsup{Wikimedia} \item \wbalsup{lots of users!} \item \wbalTwo{John}{Doe} \end{itemize}
This is the Wikibook about LaTeX supported by Wikimedia This is the Wikibook about LaTeX supported by lots of users! This is the Wikibook about LaTeX supported by John Doe
Name your new command \wbalTwo and not \wbal2 as digits cannot be used to name macros invalid characters will error out at compile-time. LaTeX will not allow you to create a new command that would overwrite an existing one. But there is a special command in case you explicitly want this: \renewcommand . It uses the same syntax as the \newcommand command. In certain cases you might also want to use the \providecommand command. It works like \newcommand , but if the command is already defined, LaTeX will silently ignore the new command. With LaTex2e, it is also possible to add a default parameter to a command with the following syntax: \newcommand{name}[num][default]{definition} If the default parameter of \newcommand is present, then the first of the number of arguments specified by num is optional with a default value of default; if absent, then all of the arguments are required.
Macros
404
This is the Wikibook about LaTeX supported by Wikimedia and John Doe! This is the Wikibook about LaTeX supported by lots of users and John Doe!
\newcommand{\wbalTwo}[2][Wikimedia]{ This is the Wikibook about LaTeX supported by {#1} and {#2}!} % in the document body: \begin{itemize} \item \wbalTwo{John Doe} \item \wbalTwo[lots of users]{John Doe} \end{itemize}
Note When the command is used with an explicit first parameter it is given enclosed with brackets (here "[lots of users]"). Here is an common example: if you are writing a book about Mathematics and you have to use vectors, you have to decide how they will look. There are several different standards, used in many books. If a is a vector, some people like to add an arrow over it ( ), other people write it underlined (a); another common version is to write it bold (a). Let us assume you want to write your vectors with an arrow over them; then add the following line in your mystyle.sty. \newcommand{\myvec}[1]{\vec{#1}} and write your vectors inside the new \myvec{...} command. You can call it as you wish, but you'd better choose a short name because you will probably write it very often. Then, if you change your mind and you want your vectors to look differently you just have to change the definition of your \myvec{...} . Use this approach whenever you can: this will save you a lot of time and increase the consistency of your document.
New Environments
Just as with the \newcommand command, there is a command to create your own environments. The \newenvironment command uses the following syntax: \newenvironment{name}[num]{before}{after} Again \newenvironment can have an optional argument. The material specified in the before argument is processed before the text in the environment gets processed. The material in the after argument gets processed when the \end{name} command is encountered. The num argument is used the same way as in the \newcommand command. LaTeX makes sure that you do not define an environment that already exists. If you ever want to change an existing command, you can use the \renewenvironment command. It uses the same syntax as the \newenvironment command. The example below illustrates the usage of the \newenvironment command: \newenvironment{king} { \rule{1ex}{1ex}\hspace{\stretch{1}} } { \hspace{\stretch{1}}\rule{1ex}{1ex} } \begin{king} My humble subjects \ldots \end{king}
Macros
405
Extra space
When creating a new environment you may easily get bitten by extra spaces creeping in, which can potentially have fatal effects. For example when you want to create a title environment which suppresses its own indentation as well as the one on the following paragraph. The \ignorespaces command in the begin block of the environment will make it ignore any space after executing the begin block. The end block is a bit more tricky as special processing occurs at the end of an environment. With the \ignorespacesafterend LaTeX will issue an \ignorespaces after the special end processing has occurred. \newenvironment{simple}% {\noindent}% {\par\noindent} \begin{simple} See the space\\to the left. \end{simple} Same\\here.
See the space to the left. Same here.
\newenvironment{correct}% {\noindent\ignorespaces}% {\par\noindent% \ignorespacesafterend} \begin{correct} No space\\to the left. \end{correct} Same\\here.
Also, if you're still having problems with extra space being appended at the end of your environment when using the \input for external source, make sure there is no space between the beginning, sourcing, and end of the environment, such as: \begin{correct}\input{somefile.tex}\end{correct} or \begin{correct}% \input{somefile.tex}% \end{correct}
Macros
406
Arithmetic
LaTeX can manipulate numbers. The calc package provides the common infix notation. \usepackage{calc} % ... \newcounter{mine} \setcounter{mine}{2*17} \themine For high-precision computations, you can use the fp package. \usepackage{fp} % Clip \[ \FPmul\result{2}{7} \FPclip\result\result 2*7 = \result \] % Infix \[ \newcommand\result{11} \sqrt{\sin(2+\result)} \approx \FPeval\result{round(root(2,sin(result + \FPpi)):2)} \result \] % Postfix \[ \FPupn\result{17 2.5 + 17.5 - 2 1 + * 2 swap /} \FPclip\result\result (17+2.5 - 17.5) * (2+1) / 2 = \result \] % High precision \[ \FPdiv\result{17}{7} \frac{17}{7} \approx \FPtrunc\result\result{3} \result \]
Conditionals
LaTeX can use conditionals thanks to the ifthen package. \usepackage{ifthen} % ... \ifthenelse{ \equal{\myvar}{true} }{ This is true. }{ This is false. }
Loops
The PGF/TikZ extension provides the \foreach command. \usepackage{tikz} % ... \foreach \i/\q in {wheat/50g, water/1L, yeast/2g}{ \noindent\i\dotfill\q\\ } Alternatively you can check out the multido package.
Strings
xstring provides a lot of features. From CTAN: testing a strings contents extracting substrings substitution of substrings string length position of a substring number of recurrences of a substring
Examples: \usepackage{xstring} % ... \newcommand\mystr{Hello World!} The string ``\mystr'' has \StrLen{\mystr}{} characters. Predicate ``\mystr{} contains the word Hello'' is \IfSubStr{\mystr}{Hello}{true}{false}.
Macros
407
LaTeX Hooks
LaTeX provide two hooks: \AtBeginDocument will let you specify a set of commands that will be executed when \begin{document} is met. \AtEndDocument does the same for \end{document} . This gives you some more flexiblity for macros. It can be useful to override settings that get executed after the preamble. These hooks can be called several times. The commands will be executed in the order they were set. For instance, let's replace the page numbers with oldstylenums: \usepackage{textcomp} \AtBeginDocument{% % figures \let\myThePage\thepage \oldstylenums{\myThePage} } } Make the page numbers in text \renewcommand{\thepage}{
There are also hooks for classes and packages. See Creating Packages.
Command-line LaTeX
If you work on a Unix-like OS, you might be using Makefiles or any kind of script to build your LaTeX projects. In that connection it might be interesting to produce different versions of the same document by calling LaTeX with command-line parameters. If you add the following structure to your document: \usepackage{ifthen} %... % default value. \providecommand\blackandwhite{false} %... \ifthenelse{ \equal{\blackandwhite}{true} }{ % "black and white" mode; do something.. }{ % "color" mode; do something different.. } Now you can call LaTeX like this: latex '\providecommand{\blackandwhite}{true}\input{test.tex}' First the command \blackandwhite gets defined and then the actual file is read with input. By setting \blackandwhite to false the color version of the document would be produced.
Plain TeX
408
Plain TeX
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Plain TeX
409 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] While you play with LaTeX macros, you will notice that it is quite limited. You may wonder how all these packages you are using every day have been implemented with so little. In fact, LaTeX is a set of Plain TeX macros and most packages use Plain TeX code. Plain TeX is much more low-level, it has much more capabilities at the cost of a steep learning curve and complex programming. You can use the full Plain TeX language with LaTeX whereas the opposite is false.
Plain TeX
410
Vocabulary
To avoid confusion it seems necessary to explain some terms. A group is everything after an opening brace and before the matching closing brace. A token is a character, a control sequence, or a group. A control sequence is anything that begins with a \ . It is not printed as is, it is expanded by the TeX engine according to its type. A command (or function or macro) is a control sequence that may expand to text, to (re)definition of control sequences, etc. A primitive is a command that is hard coded in the TeX engine, i.e. it is not written in Plain TeX. A register is the TeX way to handle variables. They are limited in numbers (256 for each type of register). A length is a control sequence that contains a length (a number followed by a unit). See Lengths. A font is a control sequence that refers to a font file. See Fonts. A box is an object that is made for printing. Anything that ends on the paper is a box: letters, paragraphs, pages... See Boxes. A glue is a certain amount of space that is put between boxes when they are being concatenated. A counter is a register containing a number. See Counters. There may be more terms, but we hope that it will do it for now.
Catcodes
In TeX some characters have a special meaning that is not to print the associated glyph. For example, \ is used to introduce a control sequence, and will not print a backslash by default. All characters with special meaning belong to a category code, or catcode for short. There are 16 category codes in TeX. A powerful feature of TeX is its ability to redefine the language itself, since there is a \catcode function that will let you change the category code of any characters. However this is may be bad practice and lead to unreadable code, especially if you are not working alone on your document. Should you redefine any catcode in a class or in a style file, make sure to revert it back at the end of your file. If you redefine catcodes in your document, make sure to do it after the preamble to prevent clashes with package loading.
Code 0 1 2 3 4 5 6 7 8 9 10 Description Escape character and control sequences Beginning of group End of group Math shift Alignment tab End of line Macro parameter Superscript Subscript Ignored character Space Default set
\ { } $ & ^^M # ^ _
and ^^K and ^^A (ASCII null) (ASCII return)
^^@
Plain TeX
411
11 12 13 14 15 Letter Other character Active character Comment character Invalid character
A...Z
and a...z
~ %
^^?
(ASCII delete)
Active characters
Active characters resemble macros: they are single characters that will expand before any other command. \catcode`| = 13 \def|{\TeX} ... This is a stupid example of |.
This is a stupid example of TeX.
Note that an active character needs to be directly followed by a definition, otherwise the compilation will fail.
Examples
Texinfo Texinfo uses a syntax similar to TeX with one major difference: all functions are introduced with a @ instead of a \ . This is not by chance: it actually uses TeX to print the PDF version of the files. What it basically does is inputting texinfo.tex which redefines the control sequence character. Possible implementation: \catcode`\@=0 @def@@{@char64} % To write '@' character. \catcode`\\=13 @def\{{@tt @char92}} The @TeX command was previously written '\TeX', now it is written '@@TeX'.
The TeX command was previously written '\TeX' It is now written '@TeX'.
With this redefinition, the '@' should now introduce every command, while the '\' will actually print a backslash character. Itemize Some may find the LaTeX syntax of list environments a bit cumbersome. Here is a quick way to define a wiki-like itemize: \catcode`| = 13 \def|{\item {--}} \def\itemize#1{{\leftskip = 40 pt #1 \par}} \itemize{ | First item | Second item } Dollar and math If you have many 'dollar' symbols to print, you may be better off to change the math shift character. \catcode`$ = 11 \catcode`| = 3 It costs $100. Let's do the math: |50+50=100|. Let's highlight it: ||50+50=100||
Plain TeX That's why when you need to access LaTeX internals, you must enclose all the commands accessing private functions with \makeatletter and \makeatother . All they do is just changing the catcode: \def\makeatletter{\catcode`@ = 11} \def\makeatother{\catcode`@ = 12}
412
Expanded definitions
TeX has another definition command: \edef , which stands for expanded def. The syntax remains the same: \edef<macroname> <argumentslist>{<expanded content>} The content gets expanded but not executed, i.e. printed. Macro expansion is not always obvious... Example: \def\intro{Example} \edef\example#1{\intro~---~#1} \example{This is an example} Here the redefinition of \intro will have no effect on \example . \def\intro{Exercise}
Plain TeX
413
Global definitions
Definitions are limited to their scope. However it might be convenient sometimes to define a macro inside a group that remain valid outside the group, and until the end of the document. This is what we call global definitions. { \def\LocalTeX{Local\TeX} \global\def\GlobalTeX{Global\TeX} access the \GlobalTeX{} macro here. You can also use the \global command with \edef . Both commands have a shortcut: \gdef for \global\def \xdef for \global\edef } I can still
Long definitions
The previous definition commands would not allow you to use them over multiple paragraphs, i.e. text containing the \par command -- or double line breaks. You can prefix the definition with the \long command to allow multi-paragraph arguments. Example: \long\def\dummy#1{#1} \dummy{First paragraph\par Second paragraph}
Outer definitions
This prefix macro prevent definitions from being used in some context. It is useful to consolidate macros and make them less error-prone because of bad contexts. Outer macros are meant to be used outside of any context, hence the name. For instance the following code will fail: \outer\def\test{a test} \def\failure{\test} Outer macros are not allowed to appear in: macro parameters skipped conditional ...
Plain TeX
414
The last line will print a sentence depending on the \status . This command actually does the opposite of \string which prints a control sequence name without expanding it: {\tt \string\TeX}
\TeX
Controlling expansion
\expandafter{token1}{token2} will expand token2 before token1. It is sometimes needed when token2 expansion is desired but cannot happen because of token1. {\tt \expandafter\string\csname TeX\endcsname}
\TeX
\noexpand is useful to have fine grained control over what gets expanded in an \edef . Example: \def\intro{Example} \def\separator{~---~} \edef\example#1{\intro\noexpand\separator#1} \example{no expand makes the separator dynamic in an {\tt \string\edef}.} \def\intro{For instance} \def\separator{~:~} \example{the separator changed, but not the first word.} \the control sequence will let you see the content of various TeX types: catcodes chardef font parameters internal parameters lengths registers ...
Registers
Registers are kind of typed variables. They are limited in numbers, ranging from 0 to 255. There are 6 different types:
Plain TeX
415
TeX uses some registers internally, so you would be better off not using them. List of reserved registers: \box255 is used for the contents of a page \count0-\count9 are used for page numbering Scratch registers (freely available): \box0-\box254 \count255 \dimen0-\dimen9 \muskip0-\muskip9 \skip0-\skip9
Assign register using the '=' control character. For box registers, use the \setbox command instead. \count255=17 \setbox\mybox=\hbox{blah} You may use one of the following reservation macro to prevent any clash: \newbox \newcount \newdimen \newmuskip \newskip \newtoks These macros use the following syntax: \new*<csname> . Example: \newbox\mybox \setbox\mybox=\hbox{blah} These commands can not be used inside macros, otherwise every call to the macro would reserve another register. You can print a register using the \the command. For counters use the \number command instead. For boxes use the \box command. \the\hsize \number\count255 \box\mybox
Arithmetic
The arithmetic capabilities of TeX are very limited, although this base suffice to extend it to some interesting features. The three main functions: \advance <register> by <register> by <number> <number> \multiply <register> by <number> \divide
register may be of type count, dimen, muskip or skip. It does not make sense for box nor toks.
Plain TeX
416
Conditionals
The base syntax is \if* <test><true action>\fi \if* <test><true action>\else<false action>\fi where \if* is one command among the following.
Control sequence Description True if two character codes are equal. True if two category codes are equal. True if two dimensions are equal. True if Enf-Of-File or non-existent file. Always false. True if box register contains a horizontal box. True if in horizontal mode. True if in internal mode. True if in math mode. Number relation, either <, > or =. True if number is odd. Always true. True if box register contains a vertical box. True if in vertical mode. True if box register is empty. True if two macros expands to the same, or if two character codes are equal, or if two category codes are equal.
\if \ifcat \ifdim \ifeof \iffalse \ifhbox \ifhmode \ifinner \ifmmode \ifnum \ifodd \iftrue \ifvbox \ifvmode \ifvoid \ifx Example:
\ifnum 5>6 This is true \else This is false \fi You can create new conditionals with the \newif command.
This is false
Case statement
The syntax is \ifcase <number><case0>\or<case1>\or...\else<defaultcase>\fi . If number is equal to the case number, its content will be printed. Note that it starts at 0. \ifcase 2 a\or b\or c\or d\else e\fi
d
\else is used to specify the default case (whenever none of the previous cases have matched).
Plain TeX
417
Loops
The base syntax is \loop <content> \if*<condition><true action>\repeat As always, content and true action are arbitrary TeX contents. \if* refers to any of the conditionals. Note that there is no false action, you cannot put an \else between \if* and \repeat . In some case this will be the opposite of what you want; you have to change the condition or to define a new conditional using \newif . Example: \count255 = 1 \loop \TeX \ifnum\count255 < 10 \advance\count255 by 1 \repeat The above code will print TeX ten times.
Doing nothing
Sometimes it may be useful to tell TeX that you want to do nothing. There is two commands for that: \relax and \empty . Classic example: \def\myspace{\hskip 25pt\relax} \myspace{} plus 10pt The \relax prevents undesired behaviour if a plus or a minus is encounter after the command. The difference between \empty and \relax lies in the expansion: \empty disappears after macro expansion.
TeX characters
char
We can print all characters using the \char {charcode} command. The charcode is actually the byte value. For example \char65 = \char `A = \char `\A Most characters correspond to the ASCII value (e.g. A-Za-z), some replace the non-printable characters from ASCII.
Plain TeX
418
Plain TeX \def\locale{de} \def\localedef#1{ \ifthenelse{ \equal{\locale}{#1} }{ %% Set the Babel language. %% Define the command to print the content. }{ %% Define the command to print nothing. } } Another problem arises: how to define a command whose name is a variable? In most programming languages that's not possible at all. What we could be tempted to write is \def\#1 #1{#1} It will fail for two reasons. 1. The two last '#1' are supposed to refer to the arguments of the new macro, but they get expanded to the \localedef macro first argument because they are in the body of that macro. 2. \#1 gets expanded to two tokens: '#' and '1', and the \def command will fail as it requires a valid control sequence name. The solution to problem 1 is simple: use '##1', which will expand to '#1' when the macro is executed. For problem 2, it is a little bit tricky. It is possible to tell tex that a specific token is a control sequence. This is what the \csname...\endcsname is used for. However \def\csname#1\endcsname ##1{##1} will fail because it will redefine \csname to '#1', which is not what we want, then tex will encounter \endcsname , which will result in an error. We need to delay the expansion of \def , i.e. to tell tex to expand the \csname stuff first, then to apply \def on it. There is a command for that: \expandafer{token1}{token2} . It will expand {token2} before {token1}. Finally if we want to set language from command line, we must be able to set the \locale variable so that the one in the source code is the default value that can be overridden by the one in the command line. This can be done with \provdecommand : \providecommand\locale{fr} The final code is %% Required package. \usepackage{ifthen} %% TeX function that generates the language commands. \def\localedef#1#2{ \ifthenelse{ \equal{\locale}{#1} }{ \selectlanguage{#2} \expandafter\def\csname#1\endcsname ##1{##1} }{ \expandafter\def\csname#1\endcsname ##1{} } } %% Selected language. Can be placed anywhere before the language commands. \providecommand\locale{fr} %% Language commands. \localedef{de}{ngerman} \localedef{en}{english} \localedef{fr}{frenchb} %% ... And you can compile with latex '\providecommand\locale{en}\input{mydocument.tex}'
419
Plain TeX
420
Further reading TeX by Topic, Victor Eijkhout TeX for the Impatient, Paul W. Abrahams, Karl Berry and Kathryn A. Hargreaves
Creating Packages
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Creating Packages
421 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] If you define a lot of new environments and commands, the preamble of your document will get quite long. In this situation, it is a good idea to create a LaTeX package or class containing all your command and environment definitions. It can be made dynamic enough to fit to all your future documents. Classes are .cls files, package are stored in .sty files. They are very similar, the main difference being that you can load only one class per document.
Creating Packages
422
423
For a more convenient use, it is possible to place the package within $TEXMFHOME (which is ~/texmf by default) accoding to the TeX Directory Structure (TDS). That would be $TEXMFHOME/tex/latex/custom/custom.sty On Windows '~' is often C:\Users\username. You may have to run texhash (or equivalent) to make your TeX distribution index the new file, thus making it available for use for any document. It will allow you to use your package as detailed above, but without it needing to be in the same directory as your document.
Hooks
There are also hooks for classes and packages. \AtEndOfPackage \AtEndOfClass They behave as the document hooks. See LaTeX Hooks.
Themes
424
Themes
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Themes
425 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Newcomers to LaTeX often feel disappointed by the lack of visual customization offered by the system. Actually this is done on purpose: the LaTeX philosophy takes a point at doing the formatting while the writer focuses on the content. In this chapter, we will show what we can achieve with some efforts.
Themes
426
Introduction
In the following we will write the theme, a package that will only change the appearance of the document, so that our document will work with or without the theme. Note that if it may look eye-candy, this is absolutely not a model of typography. You should not use such theme for serious publications. This is more a technogical example to exhibit LaTeX capabilities.
Custom theme
Package configuration
Nothing much to say here. This is a direct application of the Creating Packages chapter. We load the required packages. needspace is used to prevent page break right after a sectioning command. tikz is used to draw the fancy material. We define a color option, you may use as much as you want. Defining colors with specific names makes it very flexible. We also use an option to toggle the fancy reflection effect which might be a little too much! \NeedsTeXFormat{LaTeX2e} \ProvidesPackage{theme-fancy}[2013/01/13 v1.0 fancy theme] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Packages \RequirePackage{geometry} \RequirePackage{needspace} \RequirePackage[svgnames]{xcolor} \RequirePackage{hyperref} \hypersetup{colorlinks=true} \RequirePackage{fancyhdr} \RequirePackage{tikz} \usetikzlibrary{ calc, decorations.pathmorphing, fadings, shadows, shapes.geometric, shapes.misc, } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Options %% Toggle reflection. \newif\if@mirrors\@mirrorsfalse \DeclareOption{mirrors}{ \@mirrorstrue } %% Colors. \newif\if@red\@redfalse \DeclareOption{red}{ \@redtrue } \ExecuteOptions{} \ProcessOptions\relax %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Configuration \renewcommand{\familydefault}{\sfdefault} \setlength{\parskip}{0.5\baselineskip} %% Colors \colorlet{toctitle}{DarkGray!50!black} \colorlet{titlebg}{MidnightBlue}
Themes \colorlet{titlefg}{LightBlue} \colorlet{titletxt}{MidnightBlue} \colorlet{sectionfg}{MidnightBlue} \colorlet{subsectionfg}{SteelBlue} \colorlet{subsubsectionfg}{LightSteelBlue!60!black} \if@red \colorlet{toctitle}{DarkGray!50!black} \colorlet{titlebg}{DarkRed} \colorlet{titlefg}{FireBrick!50} \colorlet{titletxt}{DarkRed} \colorlet{sectionfg}{DarkRed} \colorlet{subsectionfg}{Crimson!50!black} \colorlet{subsubsectionfg}{LightSteelBlue!60!black} \fi
427
Table of contents
We redefine commands used by \tableofcontents .
\renewcommand*\l@subsection{\color{\subsectiontoccolor}\def\@linkcolor{\subsectiontoccolo
\renewcommand*\l@subsubsection{\color{\subsubsectiontoccolor}\def\@linkcolor{\subsubsecti \def\contentsline#1#2#3#4{% \ifx\\#4\\% \csname l@#1\endcsname{#2}{#3}% \else \csname l@#1\endcsname{\hyper@linkstart{link}{#4}{#2}\hyper@linkend}{% \hyper@linkstart{link}{#4}{#3}\hyper@linkend }% \fi } %% New title format -'section' is used by default. \newcommand{\tocformat}[1]{{\Huge\bf#1}} \renewcommand\tableofcontents{% \tocformat{ \textcolor{toctitle}{\contentsname} \@mkboth{\MakeUppercase\contentsname}{\MakeUppercase\contentsname} }% \@starttoc{toc}% }
Themes
428
Sectioning
This is definitely the most complex part. It is not that hard since the code is almost the same for \section , \subsection and \subsubsection . We use \needspace to make sure there is no line break right after a sectioning command. We enclose the command in a group where we set a font size since the space we need is \baselineskip which depends on the font size. Starred commands will not set the counters (LaTeX detault behaviour). You can choose to handle starred command differently by resetting the counters for instance. We preceed the section printing by a \noindent . We make sure to end the section printing by a \par command to make sure following text gets printed properly. For \subsection we make use of the mirrors option to change the appearance accordingly. To handle the PDF bookmarks properly we need the following lines at the end of the definitions. \phantomsection \addcontentsline{toc}{section}{\thesection~#1} Finally, for \section only, we want it to print in the header, so we call the \sectionmark command. Here we changed the behaviour of the starred command over the original LaTeX version, since we define and use the \sectionmarkstar command. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Section style \renewcommand\section{ \@ifstar \my@sectionstar \my@section } %% Note: to justify, text width must be set to \textwidth - 2*(inner sep). \tikzstyle{sectionstyle}=[ inner sep=5pt, text width=\textwidth-10pt, left color=sectionfg!100!white, right color=sectionfg!50!white, rounded corners, text=Ivory, rectangle ] \newcommand\my@section[1]{ \stepcounter{section} {\Large\needspace{\baselineskip}} \noindent \begin{tikzpicture} \node[sectionstyle] {\bfseries\Large\thesection\quad#1}; \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{section}{\thesection~#1} \sectionmark{#1} } \newcommand{\sectionmarkstar}[1]{\markboth{\MakeUppercase{#1}}{}} \newcommand\my@sectionstar[1]{ {\Large\needspace{\baselineskip}} \noindent \begin{tikzpicture} \node[sectionstyle] {\bfseries\Large#1}; \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{section}{#1} \sectionmarkstar{#1} } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Subsection style \renewcommand\subsection{ \@ifstar \my@subsectionstar \my@subsection } \tikzstyle{subsectionstyle}=[ left color=subsectionfg!50!white, right color=subsectionfg!100!white, text=Ivory, ellipse, inner sep=5pt ] \newcommand\my@subsection[1]{ \stepcounter{subsection} {\Large\needspace{\baselineskip}} \noindent \begin{tikzpicture} \node[subsectionstyle,anchor=west] (number) at (0,0) {\bfseries\Large\thesubsection}; \if@mirrors \node[above right,subsectionfg,anchor=south west] at ($(number.east)+(0.1,-0.1)$) {\large\bfseries#1}; \node[yscale=-1, scope fading=south, opacity=0.4, above, anchor=south west, subsectionfg] at ($(number.east)+(0.1,0.1)$) {\large\bfseries#1}; \else \node[above right,subsectionfg,anchor=west] at ($(number.east)+(0.1,0)$) {\large\bfseries#1}; \fi \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{subsection}{\thesubsection~#1} }
Themes
429
\newcommand\my@subsectionstar[1]{ {\Large\needspace{\baselineskip}} \noindent \begin{tikzpicture} \node[subsectionstyle,anchor=west] (number) at (0,0) {\bfseries\Large\phantom{1}}; % \if@mirrors \node[above right,subsectionfg,anchor=south west] at ($(number.east)+(0.1,-0.1)$) {\large\bfseries#1}; \node[yscale=-1, scope fading=south, opacity=0.4, above, anchor=south west, subsectionfg] at ($(number.east)+(0.1,0.1)$) {\large\bfseries#1}; \else \node[above right,subsectionfg,anchor=west] at ($(number.east)+(0.1,0)$) {\large\bfseries#1}; \fi \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{subsection}{#1} } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Subsubsection style \renewcommand\subsubsection{ \@ifstar \my@subsubsectionstar \my@subsubsection } \tikzstyle{subsubsectionstyle}=[ left color=subsubsectionfg!50!white, right color=subsubsectionfg!100!white, text=Ivory, shape=trapezium, inner sep=5pt ] \newcommand\my@subsubsection[1]{ \stepcounter{subsubsection} \noindent \begin{tikzpicture} \node[subsubsectionstyle] (number) {\bfseries\large\thesubsubsection}; \node[subsubsectionfg, right of=number, anchor=west] {\large\bfseries#1}; \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{subsubsection}{\thesubsubsection~#1} } \newcommand\my@subsubsectionstar[1]{ \noindent \begin{tikzpicture} \node[subsubsectionstyle] (number) {\bfseries\large\vphantom{1}}; \node[subsubsectionfg, right of=number, anchor=west] {\large\bfseries#1}; \end{tikzpicture} \par \phantomsection \addcontentsline{toc}{subsubsection}{#1} } \endinput
430
Miscellaneous
Modular Documents
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Modular Documents
431 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] During this guide we have seen what it is possible to do and how this can be achieved, but the question is: I want to write a proper text with LaTeX, what to do then? Where should I start from? This is a short step-by-step guide about how to start a document properly, keeping a good high-level structure. This is all about organizing your files using the modular capabilities of LaTeX. This way it will be very easy to make modifications even when the document is almost finished. These are all just suggestions, but you might take inspiration from that to create your own document.
Modular Documents
432
Project structure
Create a clear structure of the whole project this way: 1. create a directory only for the project. We'll refer to that in the following parts as the root directory 2. create two other directories inside the root, one for LaTeX documents, the other one for images. Since you'll have to write their name quite often, choose short names. A suggestion would be simply tex and img. 3. create your document (we'll call it document.tex, but you can use the name you prefer) and your own package (for example mystyle.sty); this second file will help you to keep the code cleaner. If you followed all those steps, these files should be in your root directory, using "/" for each directory: ./document.tex ./mystyle.sty ./tex/ ./img/ nothing else.
Modular Documents
433
Modular Documents
434
Using \includeonly
Using this command provides more complex, and hence more useful possibilities. If you include the following command in your preamble, i.e. before \begin{document}, \includeonly{filename1,filename2,...} only the files specified between the curly braces will be included. Note that you can have one or more files as the argument to this command: separate them with a comma, no spaces. This requires that there are \include commands in the document which specify these files. The filename should be written without the .tex file extension: \documentclass{book} \includeonly{Chapter_1,Chapter_4} space characters not permitted \begin{document} \include{Chapter_1} \include{Chapter_2} \include{Chapter_3} \include{Chapter_4} \end{document}
This code would process the base file but only include the content of the author's first and fourth chapters (Chapter_1.tex and Chapter_4.tex). Importantly, this alternative retains as much of the .aux information as possible from the previous run, so messes up your cross-references much less than the makeshift suggestion above.
Modular Documents
435
Subfiles package
A disadvantage of using \input and \include is that only the "root" document can be compiled and not the "child" documents individually. The package subfiles [1] resolves this problem. In the "root" document the package must be loaded as: \usepackage{subfiles} Instead of using \input and \include, "child" documents must be loaded as follows: \subfile{filename} The "child" documents must start with the following statements: \documentclass[rootdocument.tex]{subfiles} \begin{document} and end with: \end{document} In summary, root document (main.tex) looks like: \documentclass{book} \usepackage{subfiles} \begin{document} %% my document content \subfile{chapter1} %% more of my document content \end{document} and chapter 1 (chapter1.tex) looks like: \documentclass[main.tex]{subfiles} \begin{document} %% my chapter 1 content %% %% more of my chapter 1 content \end{document} Some linux distributions don't have subfiles package in their latex distributions, since its not included until TeXLive 2012 or later. You can download subfiles.zip [2] to generate subfiles.cls and subfiles.sty files: wget http://mirror.ctan.org/macros/latex/contrib/subfiles.zip unzip subfiles.zip cd subfiles latex subfiles.dtx latex subfiles.ins This will generate two files subfiles.cls and subfiles.sty. Move these files to a directory under the name subfiles in the path /usr/share/texmf/tex/latex. This still won't make the package available. A very important keyword should be used from the terminal in order for the latex packages to be updated: sudo texhash. Now you are good to go!
Modular Documents
436
Modular Documents % put here packages only for the PDF: \DeclareGraphicsExtensions{.pdf,.png,.jpg,.mps} \usepackage{hyperref} \else % put here packages only for the DVI: \fi % put all the other packages here: \usepackage{mystyle} \begin{document} \input{./tex/title.tex} %\maketitle \tableofcontents \listoffigures \listoftables \input{./tex/intro.tex} \input{./tex/main_part.tex} \input{./tex/conclusions.tex} \appendix \input{./tex/myappendix.tex}
437
% Bibliography: \clearpage \addcontentsline{toc}{chapter}{Bibliography} \input{./tex/mybibliography.tex} \end{document} Here a lot of code expressed in previous sections has been used. At the beginning there is the header discussed in the Tips & Tricks section, so you will be able to compile in both DVI and PDF. Then you import the only package you need, that is your mystyle.sty (note that in the code it has to be imported without the extension), then your document starts. Then it inserts the title: we don't like the output of \maketitle so we created our own, the code for it will be in a file called title.tex in the folder called tex we created before. How to write it is explained in the Title Creation section. Then tables of contents, figure and tables are inserted. If you don't want them, just comment out those lines. Then the main part of the document in inserted. As you can see, there is no text in document.tex: everything is in other files in the tex directory so that you can easily edit them. We are separating our text from the structural code, so we are improving the "What You See is What You Mean" nature of LaTeX. Then we can see the appendix and finally the Bibliography. It is in a separated file and it is manually added to the table of contents using a tip suggested in the Tips & Tricks. Once you created your document.tex you won't need to edit it anymore, unless you want to add other files in the tex directory, but this is not going to happen very often. Now you can write your document separating it in as many
Modular Documents files as you want and adding many pictures without getting confused: thanks to the rigid structure you gave to the project, you will be able to keep track of all your edits clearly. A suggestion: do not call your files like "chapter_01.tex" or "figure_03.png", i.e. try to avoid using numbers in file-names: if the numbering LaTeX gives them automatically is different from the one you gave (and this will likely happen) you will get really confused. When naming a file, stop for a second, think about a short name that can fully explain what is inside the file without being ambiguous, it will let you save a lot of time as soon as the document gets larger.
438
External Links
Subfiles package documentation [4] pdfpages package documentation [5]
References
[1] [2] [3] [4] http:/ / ctan. org/ tex-archive/ macros/ latex/ contrib/ subfiles http:/ / tezcatl. fciencias. unam. mx/ tex-archive/ macros/ latex/ contrib/ subfiles. zip http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ pdfpages/ http:/ / tug. ctan. org/ tex-archive/ macros/ latex/ contrib/ subfiles/ subfiles. pdf
[5] http:/ / mirror. ctan. org/ macros/ latex/ contrib/ pdfpages/ pdfpages. pdf
LaTeX
439
Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
440
Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Note: This Wikibook is based on the article Tools for Collaborative Writing of Scientific LaTeX Documents Arne Henningsen that is published in The PracTeX Journal 2007, number 3 (http://www.tug.org/pracjourn/).
[1]
by
441
Abstract
Collaborative writing of documents requires a strong synchronisation among authors. This Wikibook describes a possible way to organise the collaborative preparation of LaTeX documents. The presented solution is primarily based on the version control system Subversion (http:/ / subversion. apache. org/ ). The Wikibook describes how Subversion can be used together with several other software tools and LaTeX packages to organise the collaborative preparation of LaTeX documents.
Other Methods
You can use one of the online solutions listed in the Installation chapter. Most of them have collaboration features. Another option for collaboration is dropbox [2]. It has 2 GB free storage and versioning system. Works like SVN, but more automated and therefore especially useful for beginning LaTeX users. As the LaTeX system uses plain text, you can use synchronous collaborative editors like Gobby. In Gobby you can write your documents in collaboration with anyone in real time. It is strongly recommended that you use utf8 encoding (especially if there are users on multiple operating systems collaborating) and a stable network (typically wired networks). TitanPad [3] (or other clones [4] of EtherPad). To compile use the command: wget -O filename.tex "http://titanpad.com/ep/pad/export/xxxx/latest?format=txt" && (latex filename.tex) where 'xxxx' should be replaced by the pad number (something like 'z7rSrfrYcH'). With a dedicated Linux box with LaTeX & Dropbox it's possible to use Google docs and some scripting [5] to get automatically generated PDFs on Dropbox from updates on Google Docs. You can use a distributed version control system such as Mercurial or Git. This is the definitive solution for users looking for control and advanced features like branch and merge. The learning curve will be steeper than that for a web-based solution.
Introduction
The collaborative preparation of documents requires a considerable amount of coordination among the authors. This coordination can be organised in many different ways, where the best way depends on the specific circumstances. In this Wikibook, I describe how the collaborative writing of LaTeX documents is organised at our department (Division of Agricultural Policy, Department of Agricultural Economics, University of Kiel, Germany). I present our software tools, and describe how we use them. Thus, this Wikibook provides some ideas and hints that will be useful for other LaTeX users who prepare documents together with their co-authors.
Interchanging Documents
There are many ways to interchange documents among authors. One possibility is to compose documents by interchanging e-mail messages. This method has the advantage that common users generally do not have to install and learn the usage of any extra software, because virtually all authors have an e-mail account. Furthermore, the author who has modified the document can easily attach the document and explain the changes by e-mail as well. Unfortunately, there is a problem when two or more authors are working at the same time on the same document. So, how can authors synchronise these files? A second possibility is to provide the document on a common file server, which is available in most departments. The risk of overwriting each others' modifications can be eliminated by locking files that are currently edited.
Collaborative Writing of LaTeX Documents However, generally the file server can be only accessed from within a department. Hence, authors who are out of the building cannot use this method to update/commit their changes. In this case, they will have to use another way to overcome this problem. So, how can authors access these files? A third possibility is to use a version control system. A comprehensive list of version control systems can be found at Wikipedia [6]. Version control systems keep track of all changes in files in a project. If many authors modify a document at the same time, the version control system tries to merge all modifications automatically. However, if multiple authors have modified the same line, the modifications cannot be merged automatically, and the user has to resolve the conflict by deciding manually which of the changes should be kept. Authors can also comment their modifications so that the co-authors can easily understand the workflow of this file. As version control systems generally communicate over the internet (e.g. through TCP/IP connections), they can be used from different computers with internet connections. A restrictive firewall policy might prevent the version control system from connecting to the internet. In this case, the network administrator has to be asked to open the appropriate port. The internet is only used for synchronising the files. Hence, a permanent internet connection is not required. The only drawback of a version control system could be that it has to be installed and configured. Moreover, a version control system is useful even if a single user is working on a project. First, the user can track (and possibly revoke) all previous modifications. Second, this is a convenient way to have a backup of the files on other computers (e.g. on the version control server). Third, this allows the user to easily switch between different computers (e.g. office, laptop, home).
442
443
444
445
Furthermore, version control systems allow a very effective quality assurance measure: all authors should critically review their own modifications before they commit them to the repository (see figure 2). The differences between the user's working copy and the repository can be easily inspected with a single Subversion command or with one or two clicks in a graphical Subversion client. Furthermore, authors should verify that their code can be compiled flawlessly before they commit their modifications to the repository. Otherwise, the co-authors Figure 2: Reviewing modifications in KDiff3 have to pay for these mistakes when they want to compile the document. However, this directive is not only reasonable for version control systems but also for all other ways to interchange documents among authors. Subversion has a feature called 'Keyword Substitution' that includes dynamic version information about a file (e.g. the revision number or the last author) into the contents of the file itself (see e.g. http:/ / svnbook. red-bean. com, chapter 3). Sometimes, it is useful to include these information not only as a comment in the LaTeX source code, but also in the (compiled) DVI, PS, or PDF document. This can be achieved with the LaTeX packages svn (http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ svn/ ), svninfo (http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/svninfo/), or (preferably) svn-multi (http://www.ctan.org/tex-archive/macros/latex/contrib/svn-multi/). The most important directives for collaborative writing of LaTeX documents with version control systems are summarised in the following box. Directives for using LaTeX with version control systems 1. Avoid 'ineffective' modifications. 2. Do not change line breaks without good reason. 3. Turn off automatic line wrapping of your LaTeX editor. 4. Start each new sentence in a new line. 5. Split long sentences into several lines so that each line has at most 80 characters. 6. Put only those files under version control that are directly modified by the user. 7. Verify that your code can be compiled flawlessly before committing your modifications to the repository. 8. Use Subversion's diff feature to critically review your modifications before committing them to the repository. 9. Add a meaningful and descriptive comment when committing your modifications to the repository. 10. Use the Subversion client for copying, moving, or renaming files and folders that are under revision control. If the users are willing to let go of the built-in diff utility of SVN and use diff tools that are local on their workstations, they can put to use such tools that are more tailored to text documents. The diff tool that comes with SVN was designed with source code in mind. As such, it is built to be more useful for files of short lines. Other tools, such as Compare It! allows to conveniently compare text files where each line can span hundreds of characters (such as when each line represents a paragraph). When using a diff tool that allows convenient views of files with long lines, the users can author the TeX files without a strict line-breaking policy.
Collaborative Writing of LaTeX Documents An example on how to use Latexdiff in the Terminal. latexdiff old.tex new.tex > diff.tex # Files old.tex and new.tex are compared and the file visualizing the changes is written to diff.tex pdflatex diff.tex # Create a PDF showing the changes The program DiffPDF [14] can be used to compare two existing PDFs visually. There is also a command line tool comparepdf [15] based on DiffPDF.
446
447
Second, we add the BibTeX field location for information about the location, where the publication is available as hard copy (e.g. a book or a copy of an article). This field can contain the name of the user who has the hard copy and where he has it or the name of a library and the shelf-mark. This field can be added in JabRef by selecting Options Set up general fields and adding the word location (using the semicolon (;) as delimiter) somewhere in the line that starts with General: (see figure 4).
Third, we put all PDF files of publications in a specific subdirectory in our file server, where we use the BibTeX key as file name. We inform JabRef about this subdirectory by selecting Options Preferences External programs and adding the path of the this subdirectory in the field Main PDF directory (see figure 5). If a PDF file of a publication is available, the user can push the Auto button left of JabRef's Pdf field to automatically add the file Figure 5: Specify 'Main PDF directory' in JabRef name of the PDF file. Now, all users who have access to the file server can open the PDF file of a publication by simply clicking on JabRef's PDF icon. If we send the LaTeX source code of a project to a journal, publisher, or somebody else who has no access to our common texmf tree, we do not include our entire bibliographic data base, but extract the relevant entries with the Perl script aux2bib (http://www.ctan.org/tex-archive/biblio/bibtex/utils/bibtools/aux2bib).
Conclusion
This wikibook describes a possible way to efficiently organise the collaborative preparation of LaTeX documents. The presented solution is based on the Subversion version control system and several other software tools and LaTeX packages. However, there are still a few issues that can be improved. First, we plan that all users install the same LaTeX distribution. As the TeX Live distribution (http:/ / www. tug. org/ texlive/ ) is available both for Unix and MS Windows operating systems, we might recommend our users to switch to this LaTeX distribution in the future. (Currently, our users have different LaTeX distributions that provide a different selection of LaTeX packages and different versions of some packages. We solve this problem by providing some packages on our common texmf tree.) Second, we consider to simplify the solution for a common bibliographic data base. Currently it is based on the version control system Subversion, the graphical BibTeX editor JabRef, and a file server for the PDF files of publications in the data base. The usage of three different tools for one task is rather challenging for infrequent users and users that are not familiar with these tools. Furthermore, the file server can be only accessed by local users. Therefore, we consider to implement an integrated server solution like WIKINDX (http:/ / wikindx. sourceforge. net/ ), Aigaion (http:/ / www. aigaion. nl/ ), or refBASE (http:/ / refbase. sourceforge. net/ ). Using this solution only requires a computer with internet access and a web browser, which makes the usage of our data base considerably easier for infrequent users. Moreover, the stored PDF files are available not only from within the department, but throughout the world. (Depending on the copy rights of the stored PDF files, the access to the server --- or least the access to the PDF files --- has to be restricted to members of the department.) Even Non-LaTeX users of our department might benefit from a server-based solution, because it should be easier to use this bibliographic data base in (other) word processing software packages, because these servers provide the data not only in BibTeX format, but also in other formats. All readers are encouraged to contribute to this wikibook by adding further hints or ideas or by providing further solutions to the problem of collaborative writing of LaTeX documents.
448
Acknowledgements
Arne Henningsen thanks Francisco Reinaldo and Graldine Henningsen for comments and suggestions that helped him to improve and clarify this paper, Karsten Heymann for many hints and advices regarding LaTeX, BibTeX, and Subversion, and Christian Henning as well as his colleagues for supporting his intention to establish LaTeX and Subversion at their department.
References
Fenn, Jrgen (2006): Managing citations and your bibliography with BibTeX. The PracTEX Journal, 4. http:// www.tug.org/pracjourn/2006-4/fenn/. Markey, Nicolas (2005): Tame the BeaST. The B to X of BibTeX. http://www.ctan.org/tex-archive/info/ bibtex/tamethebeast/ttb_en.pdf.Version 1.3. Oren Patashnik. Designing BibTeX styles. http://www.ctan.org/tex-archive/info/biblio/bibtex/contrib/doc/ btxhak.pdf. Tools for collaborative paper-writing [16]
References
[1] http:/ / tug. org/ pracjourn/ 2007-3/ henningsen/ [2] http:/ / www. getdropbox. com [3] http:/ / titanpad. com [4] http:/ / etherpad. org/ etherpadsites. html [5] https:/ / gist. github. com/ 1995648 [6] http:/ / en. wikipedia. org/ wiki/ List_of_revision_control_software [7] http:/ / subversion. apache. org/ [8] http:/ / www. dyndns. com/ [9] http:/ / tortoisesvn. tigris. org/ [10] http:/ / zoneit. free. fr/ esvn/ [11] http:/ / kdiff3. sourceforge. net/ [12] http:/ / www. ctan. org/ tex-archive/ support/ latexdiff/ [13] http:/ / www. ctan. org/ tex-archive/ macros/ latex/ contrib/ changebar/ [14] http:/ / www. qtrac. eu/ diffpdf. html [15] http:/ / www. qtrac. eu/ comparepdf. html [16] http:/ / mathoverflow. net/ questions/ 3044/ tools-for-collaborative-paper-writing
449
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
450 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Strictly speaking, LaTeX source can be used to directly generate two formats: DVI using latex, the first one to be supported; PDF using pdflatex , more recent. Using other software freely available on Internet, you can easily convert DVI and PDF to other document formats. In particular, you can obtain the PostScript version using software which is included in your LaTeX distribution. Some LaTeX IDE will give you the possibility to generate the PostScript version directly (even if it uses internally a DVI
Export To Other Formats mid-step, e.g. LaTeX DVI PS). It is also possible to create PDF from DVI and vice versa. It doesn't seem logical to create a file with two steps when you can create it straight away, but some users might need it because, as you remember from the first chapters, the format you can generate depends upon the formats of the images you want to include (EPS for DVI, PNG and JPG for PDF). Here you will find sections about different formats with description about how to get it. Other formats can be produced, such as RTF (which can be used in Microsoft Word) and HTML. However, these documents are produced from software that parses and interprets the LaTeX files, and do not implement all the features available for the primary DVI and PDF outputs. Nonetheless, they do work, and can be crucial tools for collaboration with colleagues who do not edit documents with LaTeX.
451
Tools installation
This chapter features a lot of third-party tools; most of them are installed independently of your TeX distribution. Some tools are Unix-specific (*BSD, GNU/Linux and Mac OS X), but it may be possible to make them work on Windows. If you have the choice, it is often easier with Unix systems for command line tools. Some tools may already be installed. For instance, you can check if dvipng is installed and ready to use (Unix only): which dvipng You get a directory if it is OK. [[w Most of these tools are installable using your package manager or portage tree (Unix only).
Preview mode
This section describes how to generate a screenshot of a LaTeX page or of a specific part of the page using the LaTeX package preview. Screenshots are useful, for example, if you want to include a LaTeX generated formula on a presentation using you favorite slideware like Powerpoint, Keynote or LibreOffice Impress. First, start by making sure you have preview. See Installing Extra Packages. Say you want to take a screenshot of
Write this formula in the preview environment: \documentclass{article} \usepackage[active]{preview} \begin{document} \begin{preview} \[ \pi = \sqrt{12}\sum^\infty_{k=0} \frac{ (-3)^{-k} }{ 2k+1 } \] \end{preview} \end{document} Note the active option in the package declaration and the preview environment around the equation's code. Without any of these two, you won't get any output. This package is also very useful to export specific parts to other format, or to produce graphics (e.g. using PGF/TikZ) and then including then in other documents. You can also automate the previewing of specific environments: \usepackage[active,tightpage]{preview} \PreviewEnvironment{lstlisting} \setlength{\PreviewBorder}{10pt}% % ... \begin{lstlisting} int main() { /* ... */ } \end{lstlisting} This will produce a PDF containing only the listing content, the page layout will depend on the shape of the source code.
452
Convert to PDF
Directly
pdflatex my_file
DVI to PDF
dvipdfm my_file.dvi will create my_file.pdf. Another way is to pass through PS generation: dvi2ps myfile.dvi ps2pdf myfile.ps you will get also a file called my_file.ps that you can delete.
Merging PDF
If you have created different PDF documents and you want to merge them into one single PDF file you can use the following command-line command. You need to have Ghostscript installed: Using Windows
gswin32 -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=Merged.pdf -dBATCH 1.pdf 2.pdf 3.pdf
Using Linux gs -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUTFILE=Merged.pdf -dBATCH 1.pdf 2.pdf 3.pdf Alternatively, PDF-Shuffler [1] is a small python-gtk application, which helps the user to merge or split pdf documents and rotate, crop and rearrange their pages using an interactive and intuitive graphical interface. This program may be avaliable in your Linux distribution's repository. Another option to check out is pdftk [2] (or PDF toolkit), which is a command-line tool that can manipulate PDFs in many ways. To merge one or more files, use: pdftk 1.pdf 2.pdf 3.pdf cat output 123.pdf Using pdfLaTeX Note: If you are merging external PDF documents into a LaTeX document which is compiled with pdflatex, a much simpler option is to use the pdfpages package, e.g.: \usepackage{pdfpages} ... \includepdf[pages=-]{Document2.pdf} ... \includepdf[pages=-]{Document1.pdf}
Three simple shell scripts using the pdfpages package are provided in the pdfjam bundle [3] by D. Firth. They include options for merge several pdf (pdfjoin), put several pages in one physical sheet (pdfnup) and rotate pages (pdf90). See also Modular Documents
453
XeTeX
You can also use XeTeX (or, more precisely, XeLaTeX), which works in the same way as pdflatex: it creates a PDF file directly from LaTeX source. One advantage of XeTeX over standard LaTeX is support for Unicode and modern typography. See its Wikipedia entry for more details. Customization of PDF output in XeTeX (setting document title, author, keywords etc.) is done using the configuration of hyperref package.
Convert to PostScript
from PDF pdf2ps my_file.pdf from DVI dvi2ps my_file.dvi
Convert to RTF
LaTeX can be converted into an RTF file, which in turn can be opened by a word processor such as OpenOffice.org Writer or Microsoft Word. This conversion is done through latex2rtf [4], which can run on any computer platform. The program operates by reading the LaTeX source, and mimicking the behaviour of the LaTeX program. latex2rtf supports most of the standard implementations of LaTeX, such as standard formatting, some math typesetting, inclusion of EPS, PNG or JPG graphics, and tables. As well, it has some limited support for packages, such as varioref, and natbib. However, many other packages are not supported. latex2rtf is simple to use. The Windows version has a GUI (l2rshell.exe), which is straightforward to use. The command-line version is offered for all platforms, and can be used on an example mypaper.tex file: latex mypaper bibtex mypaper # if you use bibtex latex2rtf mypaper Both latex and (if needed) bibtex commands need to be run before latex2rtf, because the .aux and .bbl files are needed to produce the proper output. The result of this conversion will create myfile.rtf, which you may open in many word processors such as Microsoft Word or LibreOffice.
Convert to HTML
There are many converters to HTML. HEVEA [5] hevea mylatexfile latex2html
latex2html -html_version 4.0,latin1,unicode -split 1 -nonavigation -noinfo -title "MyDocument" MyDocument.tex
TeX4ht TeX4ht [6] is a very powerful conversion program, but its configuration is not straightforward. Basically a configuration file has to be prepared, and then the program is called. bibtex2html For BibTeX.
454
Multiple formats
pdftocairo There is pdftocairo featured in the poppler toolset. pdftocairo -svg latexdoc.pdf output.svg pdftocairo also supports various raster graphic formats.
Vector graphics
pdf2svg Direct conversion from PDF to SVG can be done using the command line tool pdf2svg [7]. pdf2svg file.pdf file.svg ps2svg Alternatively DVI or PDF can be converted to PS as described before, then the bash script ps2svg.sh [8] can be used (as all the software used by this script is multiplatform, this is also possible in Windows, a step-by-step guide could be written). dvisvgm One can also use dvisvgm [9], an open source utility that converts from DVI to SVG. Inkscape Inkscape is able to convert to SVG, PDF, EPS, and other vector graphic formats. inkscape --export-area-drawing --export-ps=OUTPUT INPUT inkscape --export-area-page --export-plain-svg=OUTPUT INPUT
455
Raster graphics
GIMP Open your file with GIMP. It will ask you which page you want to convert, whether you want to use anti-aliasing (choose strong if you want to get something similar to what you see on the screen). Try different resolutions to fit your needs, but 100 dpi should be enough. Once you have the image within GIMP, you can post-process it as you like and save it to any format supported by GIMP, as PNG for example. dvipng A method for DVI files is dvipng [10]. Usage is the same as dvipdfm. Run latex as usual to generate the dvi file. Now, we want an X font size formula, where X is measure in pixels. You need to convert this, to dots per inch (dpi). The formula is: <dpi> = <font_px>*72.27/10. If you want, for instance, X = 32, then the size in dpi corresponds to 231.26. This value will be passed to dvipng using the flag -D. To generate the desired png file run the command as follows: dvipng -T tight -D 231.26 -o foo.png foo.dvi The flag -T sets the size of the image. The option tight will only include all ink put on the page. The option -o sends the output to the file name foo.png. ImageMagick The convert command from the ImageMagick [10] suite can convert both DVI and PDF files to PNG. convert input.pdf output.png optipng You can optimize the resulting image using optipng [11] so that it will take up less space.
, or use
456
References
[1] http:/ / pdfshuffler. sourceforge. net/ [2] http:/ / www. accesspdf. com/ [3] http:/ / www2. warwick. ac. uk/ fac/ sci/ statistics/ staff/ academic/ firth/ software/ pdfjam [4] http:/ / latex2rtf. sourceforge. net/ [5] http:/ / hevea. inria. fr [6] http:/ / www. cse. ohio-state. edu/ ~gurari/ TeX4ht/ [7] http:/ / www. cityinthesky. co. uk/ pdf2svg. html [8] http:/ / en. wikipedia. org/ wiki/ Wikipedia:WikiProject_Electronics/ Ps2svg. sh [9] http:/ / dvisvgm. sourceforge. net/ [10] http:/ / savannah. nongnu. org/ projects/ dvipng/ [11] http:/ / optipng. sourceforge. net/ [12] http:/ / code. google. com/ p/ opendetex/
457
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
FAQ
458 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
FAQ
459
FAQ
460
Fonts are ugly/jagged/bitmaps or PDF search fails or Copy/paste from PDF is messy
You must be using diacritics (e.g. accents) with OT1 encoding (the default). Switch to T1 encoding: \usepackage[T1]{fontenc} If you have ugly jagged fonts after the font encoding change, then you have no Type1 compatible fonts available. Install Computer Modern Super or Latin Modern (package name may be lm). To use Latin Modern you need to include the package: \usepackage{lmodern} See Fonts for an explanation.
FAQ
461
Rules of punctuation
LaTeX does some work for you, but not everything. Especially regarding punctuation, you are pretty free to do what you want. Punctuation rules are different following the language. In English, there is no space before a punctuation mark, and one space after it. There is a lot of rules, but you can have a quick look at Wikipedia.
FAQ
462
Non-breaking spaces
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 processors from inserting a line break between them. It is very important for consistent reading. LaTeX uses the '~' symbol as a non-breaking space. You 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. Example: Il rpondit~: ~Ce pain cote-t-il 2~~?~ Note that writing French like this might get really painful. Thankfully, Babel with the frenchb option will take care of the non-breaking spaces for all puncation marks. In the above example, only the non-breaking space for the euro symbol must remain.
Smart mathematics
All virtual objects designed by letters, variables or others should use a dedicated formatting. For math and a lot of other fields, the LaTeX math formatting is perfect. So to refer to an object A, write Speaking of $A$, let's say... If you want to refer to several objects in a sentence, it is the same. Speaking of $A$, $B$ and $C$... If you refer to a set of objects, you can still use the math notation. The family $(A, B, C)$ is... Note that this is different from usual text parentheses. A sentence. ($A$, $B$, and $C$ are not concerned, but we do not mean the $(A, B, C)$ family.)
FAQ
463
Stretching tables
Trying to stretch tables with the default tabular environment will often lead to unexpected results. The nice tabu package will do what you want and even much more. Alternatively if you cannot use the tabu package you may try tabularx or tabulary packages See Tables.
464
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
465 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
466
So you need to create a temporary variable. Sadly, \newcommand{\LaTeXtemp}{\LaTeX} \renewcommand{\LaTeX}{{\rm \LaTeXtemp}} does not work as well. We must use the TeX primitive \let instead. \let\LaTeXtemp\LaTeX \renewcommand{\LaTeX}{{\rm \LaTeXtemp }}
Generic header
As explained in the previous sections, a LaTeX source can be used to generate both a DVI and a PDF file. For very basic documents the source is the same but, if the documents gets more complicated, it could be necessary to make some changes in the source so that it will work for a format but it will not for the other. For example, all that is related to graphics has to be adapted according to the final format. As discussed in the section about floating objects, even if you should use different pictures according to the final format, you can override this limit putting in the same
Tips and Tricks folder pictures in different formats (e.g., EPS and PNG) with the same name and link them without writing the extension. There is a simple way to solve this problem: \usepackage{ifpdf} or, if you don't have this package, you can add the following text just after \documentclass[...]{...} : \newif\ifpdf \ifx\pdfoutput\undefined \pdffalse \else \ifnum\pdfoutput=1 \pdftrue \else \pdffalse \fi \fi this is plain TeX code. The ifpdf package and this code, both define a new if-else you can use to change your code according to the compiler you are using. After you have used this code, you can use whenever you want in your document the following syntax: \ifpdf % we are running pdflatex \else % we are running latex \fi place after \ifpdf the code you want to insert if you are compiling with pdflatex, place after \else the code you want to insert if you are compiling with latex. For example, you can use this syntax to load different packages or different graphic file formats according to the compiler.
467
Tips and Tricks compiler itself. LaTeXDraw is a free and open source graphical PSTricks generator and editor. It allows you to draw basic geometric objects and save the result in a variety of formats including .jpg, .png, .eps, .bmp as well as .tex. In the last case the saved file contains PSTricks/LaTeX code only. Owing to that you can include any possible LaTeX code in the picture, since the file is rendered by your LaTeX environment directly. Another way to generate vectorgraphics is using the Asymptote language. It is a programming language which produces vector images in encapsulated postscript format and supports LaTeX syntax in any textlabels.
468
gnuplot can plot various numerical data, functions, error distribution as well as 3D graphs and surfaces
set format "$%g$" set title "Graph 3: Dependence of $V_p$ on $R_0$" set xlabel "Resistance $R_0$ [$\Omega$]" set ylabel "Voltage $V_p$ [V]" set border 3 set xtics nomirror set ytics nomirror set terminal epslatex set output "graph1.eps" plot "graph1.csv" using 1:3 #Plot the data
Tips and Tricks Now gnuplot produces two files: the graph drawing in graph.eps and the text in graph.tex. The second includes the EPS image, so that we only need to include the file graph.tex in our document: \input{graph1.tex} The above steps can be automated by the package gnuplottex. By placing gnuplot commands inside \begin{gnuplot}\end{gnuplot}, and compiling with latex -shell-escape, the graphs are created and added into your document. Failure to access gnuplot from latex for Windows can be solved by making file title only in one word. Don't type my report.tex for your title file, but do myreport.tex . When you are using gnuplottex it is also possible to directly pass the terminal settings as an argument to the environment
\begin{gnuplot}[terminal=epslatex, terminaloptions=color, scale=0.9, linewidth=2 ] ... \end{gnuplot}
469
Using gnuplottex can cause fraudulent text-highlighting in some editors when using algebraic functions on imported data, such as: (2*($1)):2 Some editors will think of all following text as part of a formular and highlight it as such (because of the '$' that is interpreted as part of the latex code). This can be avoided by ending with: #$ \end{gnuplot} As it uncomments the dollar sign for the gnuplot interpreter, but is not affecting the interpretation of the .tex by the editor. When using pdfLaTeX instead of simple LaTeX, we must convert the EPS image to PDF and to substitute the name in the graph1.tex file. If we are working with a Unix-like shell, it is simply done using: eps2pdf graph1.eps sed -i s/".eps"/".pdf"/g graph1.tex With the included tex file we can work as with an ordinary image. Instead of calling eps2pdf directly, we can also include the epstopdf package that automates the process. If we include a graphics now and leave out the file extension, epstopdf will automatically transform the .eps-file to PDF and insert it in the text. \includegraphics{graph1} This way, if we choose to output to PS or DVI, the EPS version is used and if we output to PDF directly, the converted PDF graphics is used. Please note that usage of epstopdf requires compiling with latex -shell-escape. Note: Emacs AucTex users might want to check out Gnuplot-mode [2].
470
471
Please note that the folder tmp should exist. However if you're using linux you can do something like this: alias pdflatex='mkdir -p tmp; pdflatex -output-directory tmp' Or for vim modify your .vimrc: " use pdflatex let g:Tex_DefaultTargetFormat='pdf' let g:Tex_MultipleCompileFormats='pdf,dvi' let g:Tex_CompileRule_pdf = 'mkdir -p tmp; pdflatex -output-directory tmp -interaction=nonstopmode $*; cp tmp/*.pdf .'
References
[1] http:/ / pav. iki. fi/ software/ textext/ [2] http:/ / cars9. uchicago. edu/ ~ravel/ software/ gnuplot-mode. html
472
Appendix
Authors
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Authors
473 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
Authors
474
Included books
The following books have been included in this wikibook (or we are working on it!), with permission of the author: Andy Roberts' Getting to grips with Latex [1]. Not So Short Introduction to LaTex2e [2] by Tobias Oetiker, Hubert Partl and Irene Hyna. We have contacted the authors by email asking for permission: they allowed us to use their material, but they never edited directly this wikibook. That book is released under the GPL, that is not compatible with the GFDL used here in Wikibooks. Anyway, we have the permission of the authors to use their work. You can freely copy text from that guide to here. If you find text on both the original book and here on Wikibooks, then that text is double licensed under GPL and GFDL. For more information about Tobias Oetiker and Hubert Partl, their websites are http://it. oetiker.ch/and http://homepage.boku.ac.at/partl/respectively. LaTeX Primer [3] from the Indian TeX Users Group. Their document is released under the GNU Free Documentation License, the same as Wikibooks, so we can include parts of their document as we wish. In any case, we have contacted Indian TeX Users Group and they allowed us to do it. David Wilkins' Getting started with LaTeX [4]. The book is not released under any free license, but we have contacted the author asking him for the permission to use parts of his book on Wikibooks. He agreed: his work is still protected but you are allowed to copy the parts you want on this Wikibook. If you see text on both the original work and here, then that part (and only that part) is released under the terms of GFDL, like any other text here on Wikibooks. In progress Peter Flynn's Formatting information, a beginner's guide to typesetting with LaTeX [5]. We have contacted him by email asking for permission to use his work. The original book is released under the GNU Free Documentation License, the same as Wikibooks. For more information, his personal website is http://silmaril.ie/cgi-bin/blog.
Wiki users
Major contributors to the book on Wikibooks are: Alessio Damato Jtwdog Pierre Neidhardt
References
[1] [2] [3] [4] [5] http:/ / www. andy-roberts. net/ misc/ latex/ index. html http:/ / www. ctan. org/ tex-archive/ info/ lshort/ english/ lshort. pdf http:/ / sarovar. org/ projects/ ltxprimer/ http:/ / www. maths. tcd. ie/ ~dwilkins/ LaTeXPrimer/ http:/ / www. ctan. org/ tex-archive/ info/ beginlatex/ beginlatex-3. 6. pdf
Links
475
Links
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Links
476 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Here are some other online resources available:
Links
477
Community
The TeX Users Group [1] Includes links to free versions of (La)TeX for many kinds of computers. UK-TUG [2] The UK TeX Users' Group TUGIndia [3] The Indian TeX Users Group [news:comp.text.tex comp.text.tex] Newsgroup for (La)TeX related questions CTAN [4] hundreds of add-on packages and programs
Tutorials/FAQs
Tobias Oetiker's Not So Short Introduction to LaTex2e: http://www.ctan.org/tex-archive/info/lshort/english/lshort.pdf also at http://people.ee.ethz.ch/~oetiker/lshort/lshort.pdf Vel's introduction to LaTeX: What is it, why should you use it, who should use it and how to get started: http://www.vel.co.nz/vel.co.nz/Blog/Entries/2009/11/4_LaTeX_Document_Preparation_System.html Peter Flynn's beginner's guide (formatting): http://www.ctan.org/tex-archive/info/beginlatex/beginlatex-3.6.pdf The AMS Short Math Guide for LaTeX, a concise summary of math formula typesetting features http://www.ams.org/tex/amslatex.html amsmath users guide (PDF) and related files: http://www.ctan.org/tex-archive/macros/latex/required/amslatex/math/ LaTeX Primer from the Indian TeX Users Group: http://sarovar.org/projects/ltxprimer/ LaTeX Primer http://www.maths.tcd.ie/~dwilkins/LaTeXPrimer/ PSTricks--fancy graphics exploiting PDF capabilities http://sarovar.org/projects/pstricks/ PDFScreen--create LaTeX PDF files that have navigation buttons used for presentations: http://sarovar.org/projects/pdfscreen/ David Bausum's list of TeX primitives (these are the fundamental commands used in TeX): http://www.tug.org/utilities/plain/cseq.html Leslie Lamport's manual for the commands that are unique to LaTeX (commands not used in plain TeX): http://www.tex.uniyar.ac.ru/doc/latex2e.pdf The UK TeX FAQ List of questions and answers that are frequently posted at comp.text.tex http://www.tex.ac.uk/faq TeX on Mac OS X: Guide to using TeX and LaTeX on a Mac http://www.rna.nl/tex.html Text Processing using LaTeX http://www-h.eng.cam.ac.uk/help/tpl/textprocessing/ The (La)TeX encyclopaedia http://tex.loria.fr/index.html Hypertext Help with LaTeX http://www.giss.nasa.gov/latex/ EpsLatex: a very comprehensive guide to images, figures and graphics http://www.ctan.org/tex-archive/info/epslatex.pdf The Comprehensive LaTeX Symbol List (in PDF) http://www.ctan.org/tex-archive/info/symbols/comprehensive/symbols-a4.pdf Getting to Grips with LaTeX (HTML) Collection of Latex tutorials taking you from the very basics towards more advanced topics
Links http://www.andy-roberts.net/misc/latex/index.html Chapter 8 (about typesetting mathematics) of the LaTeX companion http://www.macrotex.net/texbooks/latexcomp-ch8.pdf
478
Reference
LaTeX Project Site [4] The Comprehensive TeX Archive Network [3] Latest (La)TeX-related packages and software TeX Directory Structure [5], used by many (La)TeX distributions Natural Math [6] converts natural language math formulas to LaTeX representation Obsolete packages and commands [7] Lamport's book LaTeX: A Document Preparation System
Templates
A resource for free high quality LaTeX templates for a variety of applications [8] LaTeX template for writing PhD thesis [9], 2007 UCL computer department thesis template [10] UT thesis template [11], 2006
References
[1] http:/ / www. tug. org/ [2] http:/ / uk. tug. org/ [3] http:/ / www. tug. org. in/ [4] http:/ / www. latex-project. org/ [5] http:/ / www. tug. org/ tds/ [6] http:/ / www. math. missouri. edu/ ~stephen/ naturalmath/ [7] http:/ / www. ctan. org/ tex-archive/ info/ l2tabu/ english/ l2tabuen. pdf [8] http:/ / www. LaTeXTemplates. com [9] http:/ / openwetware. org/ wiki/ LaTeX_template_for_PhD_thesis [10] http:/ / www. cs. ucl. ac. uk/ research/ students/ Latexforthesis. htm [11] http:/ / www. cs. utexas. edu/ users/ jbednar/ latex/
Package Reference
479
Package Reference
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Package Reference
480 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] Here is a (not complete) list of useful packages that can be used for a wide range of different kind of documents. Each package has a short description next to it and, when available, there is a link to a section describing such package in detail. All of them (unless stated) should be included in your LaTeX distribution as package_name.sty. For more information, refer to the documentation of the single packages, as described in Installing Extra Packages. The list is in alphabetical order.
Package Reference
481
amsmath
It contains the advanced math extensions for LaTeX. The complete documentation should be in your LaTeX distribution; the file is called amsdoc, and can be dvi or pdf. For more information, see the chapter about Mathematics. It adds new symbols in to be used in math mode. It introduces the proof environment and the \theoremstyle command. For more information see the Theorems section. It extends the possibility of LaTeX to handle tables, fixing some bugs and adding new features. Using it, you can create very complicated and customized tables. For more information, see the Tables section. It provides the internationalization of LaTeX. It has to be loaded in any document, and you have to give as an option the main language you are going to use in the document. For more information see the Internationalization section. Allows use of bold greek letters in math mode using the \bm{...} command. This supersedes the amsbsy package.
babel
bm
boxedminipage It introduces the boxedminipage environment, that works exactly like minipage but adds a frame around it. caption cancel changepage Allows customization of appearance and placement of captions for figures, tables, etc. Provides commands for striking out mathematical expressions. The syntax is \cancel{x} or \cancelto{0}{x} To easily change the margins of pages. The syntax is
indentfirst inputenc
latexsym listings
Package Reference
482
showkeys
A useful package related to referencing. If you wish to reference an image or formula, you have to give it a name using \label{...} and then you can recall it using \ref{...} . When you compile the document these will be replaced only with numbers, and you can't know which label you had used unless you take a look at the source. If you have loaded the showkeys package, you will see the label just next or above the relevant number in the compiled version. An example of a reference to a section is . This way you can easily keep track of the labels you add or use, simply looking at the preview (both dvi or pdf). Just before the final version, remove it.
showidx
It prints out all index entries in the left margin of the text. This is quite useful for proofreading a document and verifying the index. For more information, see the Indexing section. The "root" and "child" document can be compiled at the same time without making changes to the "child" document. For more information, see the Modular Documents section. It allows to define multiple floats (figures, tables) within one environment giving individual captions and labels in the form 1a, 1b. If you add the following code in your preamble:
subfiles
subfig
syntonly
\usepackage{syntonly} \syntaxonly
LaTeX skims through your document only checking for proper syntax and usage of the commands, but doesnt produce any (DVI or PDF) output. As LaTeX runs faster in this mode you may save yourself valuable time. If you want to get the output, you can simply comment out the second line. textcomp Provides extra symbols, e.g. arrows like \textrightarrow , various currencies (\texteuro ,...), things like \textcelsius and many others. You can change the style of newly defined theorems. For more information see the Theorems section. Lets you insert notes of stuff to do with the syntax \todo{Add
details.}
Helps you typeset of SI-units correctly. For example \SI{12}{\mega\hertz} . Automatically handles the correct spacing between the number and the unit. Note that even non-SI-units are set, like dB, rad, ... It allows to underline text (either with straight or wavy line). Few examples of usage are added to the Fonts chapter. It defines the \url{...} command. URLs often contain special character such as '_' and '&', in order to write them you should escape them inserting a backslash, but if you write them as an argument of \url{...} , you don't need to escape any special character and it will take care of proper formatting for you. If you are using hyperref, you don't need to load url because it already provides the \url{...} command. It improves the verbatim environment, fixing some bugs. Moreover, it provides the comment environment, that lets you add multiple-line comments or easily comment out big parts of the code. To insert images surrounded by text. It was discussed in section Floats, Figures and Captions. It is used to create trees, graphs, (commutative) diagrams, and similar things. See Xy-pic.
verbatim
wrapfig xypic
483
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
484 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] The easiest way to learn how to use latex is to look at how other people use it. Here is a list of real world latex sources that are freely available on the internet. The information here is sorted by application area, so that it is grouped by the scientific communities that use similar notation and LaTeX constructs.
485
General examples
Tutorial examples, books, and real world uses of LaTeX. caption.tex, simple.tex, wrapped.tex small2e.tex [1] and sample2e.tex [2]. The "official" sample documents... A short example of how to use LaTeX for scientific reports [3] by Stephen J. Eglen. The not so Short Introduction to LaTeX [4] by Tobias Oetiker is distributed with full latex sources.
References
[1] [2] [3] [4] [5] [6] [7] ftp:/ / tug. ctan. org/ tex-archive/ macros/ latex/ base/ small2e. tex ftp:/ / tug. ctan. org/ tex-archive/ macros/ latex/ base/ sample2e. tex http:/ / www. tug. org/ pracjourn/ 2006-2/ eglen/ http:/ / www. ctan. org/ tex-archive/ info/ lshort/ english/ http:/ / www. ccs. neu. edu/ course/ csg264/ latex/ http:/ / cristal. inria. fr/ ~remy/ latex/ http:/ / svn. openfoundry. org/ pugs/ docs/ talks/ hw2005. tex
Index
486
Index
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Index
487 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] This is an alphabetical index of the book.
Contents: Top - 09 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Index
488
A
Absolute Beginners Abstract Accents Algorithms Arrays Authors
B
babel Basics beamer package Bibliography Management BibTeX Bold Bullets
Bullet points
C
Captions Collaborative Writing of LaTeX Documents Color color package Columns, see Multi-column Pages Cross-referencing Customizing LaTeX
D
Dashes description environment Diactrical marks Document Classes Document Structure Drawings
Index
489
E
e.g. (exempli gratia) Ellipsis em-dash en-dash enumerate Errors and Warnings Euro currency symbol Export To Other Formats
F
Figures Floats Fonts Footer, Page Footnotes
Formatting
G
General Guidelines Graphics Creating Embedding Importing graphicx package
H
Header, Page HTML output Hyperlinks hyperref package hyphen Hyphenation
I
i.e. (id est) Images Importing Graphics Indexing Internationalization Introduction Italics
itemize
Index
490
L
Labels Letters Links Lists
M
makeidx package \maketitle Margin Notes Creating Graphics Mathematics Matrices Minipage environment example Multi-column Pages
P
Packages Creating 1 Page Layout PDF output picture Pictures PNG output Presentations Pseudocode
Q
LaTeX/Paragraph Formatting#Quoting_text
R
References RTF output
S
Small Capitals Source Code Listings Space Between Words Spell-checking Superscript and subscript: powers and indices Superscript and subscript: text mode
SVG output
Index
491
T
Table of contents Tables Teletype text Text Size Theorems Tips and Tricks Title Creation
U
URLs
V
Verbatim Text
W
Word Counting
X
XeTeX XY-pic package xy package
Command Glossary
492
Command Glossary
LaTeX Getting Started 1. Introduction 2. Installation 3. Installing Extra Packages 4. Basics Common Elements 1. Document Structure 2. Text Formatting 3. Paragraph Formatting 4. Colors 5. Fonts 6. List Structures 7. Special Characters 8. Internationalization 9. Rotations 10. Tables 11. Title creation 12. Page Layout 13. Importing Graphics 14. Floats, Figures and Captions 15. Footnotes and Margin Notes 16. Hyperlinks 17. Labels and Cross-referencing Mechanics 1. Errors and Warnings 2. Lengths 3. Counters 4. Boxes 5. Rules and Struts Technical Texts
Command Glossary
493 Mathematics Advanced Mathematics Theorems Chemical Graphics Algorithms Source Code Listings Linguistics Special Pages 1. Indexing 2. Glossary 3. Bibliography Management 4. More Bibliographies Special Documents 1. Letters 2. Presentations 3. Teacher's Corner 4. Curriculum Vitae Creating Graphics 1. Introducing Procedural Graphics 2. MetaPost 3. Picture 4. PGF/TikZ 5. PSTricks 6. Xy-pic 7. Creating 3D graphics Programming 1. Macros 2. Plain TeX 3. Creating Packages 4. Themes Miscellaneous 1. Modular Documents 2. Collaborative Writing of LaTeX Documents 3. Export To Other Formats Help and Recommendations
1. 2. 3. 4. 5. 6. 7.
FAQ Tips and Tricks Appendices 1. Authors 2. Links 3. Package Reference 4. Sample LaTeX documents 5. Index 6. Command Glossary
1. 2.
edit this box [1] edit the TOC [2] This is a glossary of LaTeX commandsan alphabetical listing of LaTeX commands with the summaries of their effects. (Brackets "[]" are optional arguments and braces "{}" are required arguments.)
Contents # A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Command Glossary
494
#
/ see slash marks \@ following period ends sentence \\[*][extra-space] new line. See Page Layout. \, thin space, math and text mode \; thick space, math mode \: medium space, math mode \! negative thin space, math mode \hyphenation; tabbing \= set tab, see tabbing \> tab, see tabbing \< back tab, see tabbing \+ see tabbing \' accent or tabbing \` accent or tabbing \| double vertical lines, math mode \( start math environment \) end math environment \[ begin displaymath environment \] end displaymath environment
Command Glossary
495
A
\addcontentsline{file}{sec_unit}{entry} adds an entry to the specified list or table \addtocontents{file}{text} adds text (or formatting commands) directly to the file that generates the specified list or table \addtocounter{counter}{value} increments the counter \address{Return address} \addtolength{len-cmd}{len} increments a length command, see Length \addvspace adds a vertical space of a specified height \alph causes the current value of a specified counter to be printed in alphabetic characters \appendix changes the way sectional units are numbered so that information after the command is considered part of the appendix \arabic causes the current value of a specified counter to be printed in Arabic numbers \author declares the author(s). See Document Structure
B
\backslash prints a backslash \baselineskip a length command (see Lengths), which specifies the minimum space between the bottom of two successive lines in a paragraph \baselinestretch scales the value of \baselineskip \bf Boldface typeface \bibitem generates a labeled entry for the bibliography \bigskipamount \bigskip equivalent to \vspace{\bigskipamount} \boldmath bold font in math mode \boldsymbol
496
C
\cal Calligraphic style in math mode \caption generate caption for figures and tables \cdots Centered dots \centering Used to center align LaTeX environments \chapter Starts a new chapter. See Document Structure. \circle \cite Used to make citations from the provided bibliography \cleardoublepage \clearpage Ends the current page and causes any floats to be printed. See Page Layout. \cline Adds horizontal line in a table that spans only to a range of cells. See \hline and ../Tables/ chapter. \closing Inserts a closing phrase (e.g. \closing{yours sincerely}), leaves space for a handwritten signature and inserts a signature specified by \signature{}. Used in the Letter class. \color Specifies color of the text. ../Colors \copyright makes sign. See Formatting.
D
\dashbox \date \ddots Inserts a diagonal ellipsis (3 diagonal dots) in math mode \documentclass[options]{style} Used to begin a latex document \dotfill
Command Glossary
497
E
\em Toggles italics on/off for the text inside curly braces with the command. Such as {\em This is in italics \em but this isn't \em and this is again}. This command allows nesting. \emph Toggles italics on/off for the text in curly braces following the command e.g. \emph{This is in italics \emph{but this isn't} and this is again}. \ensuremath (LaTeX2e) Treats everything inside the curly braces as if it were in a math environment. Useful when creating commands in the preamble as they will work inside or out of math environments. \epigraph Adds an epigraph. Requires epigraph package. \euro Prints euro symbol. Requires eurosym package.
F
\fbox \flushbottom \fnsymbol \footnote Creates a footnote. \footnotemark \footnotesize Sets font size. See Text Formatting. \footnotetext \frac inserts a fraction in mathematics mode. The usage is \frac{numerator}{denominator}. \frame \framebox Like \makebox but creates a frame around the box. See Boxes. \frenchspacing Instructs LaTex to abstain from inserting more space after a period (.) than is the case for an ordinary character. In order to untoggle this functionality resort to the command \nonfrenchspacing.
Command Glossary
498
H
\hfill Abbreviation for \hspace{\fill}. \hline adds a horizontal line in a tabular environment. See also \cline, Tables chapter. \href Add a link, or an anchor. See Hyperlinks \hrulefill \hspace Produces horizontal space. \huge Sets font size. See Text Formatting. \Huge Sets font size. See Text Formatting. \hyphenation{word list} Overrides default hyphenation algorithm for specified words. See Hyphenation
I
\include This command is different from \input in that it's the output that is added instead of the commands from the other files. For more see LaTex/Basics \includegraphics Inserts an image. Requires graphicx package. \includeonly \indent \input Used to read in LaTex files. For more see LaTex/Basics. \it Italicizes the text which is inside curly braces with the command. Such as {\it This is in italics}. \em is generally preferred since this allows nesting. \item Creates an item in a list. Used in list structures.
Command Glossary
499
K
\kill
L
\label Used to create label which can be later referenced with \ref. See Labels and Cross-referencing. \large Sets font size. See Text Formatting. \Large Sets font size. See Text Formatting. \LARGE Sets font size. See Text Formatting. \LaTeX Prints LaTeX logo. See Formatting. \LaTeXe Prints current LaTeX version logo. See Formatting. \ldots Prints sequence of three dots. See Formatting. \left \lefteqn \line \linebreak Suggests LaTeX to break line in this place. See Page Layout. \linethickness \linewidth \listoffigures Inserts a list of the figures in the document. Similar to TOC \listoftables Inserts a list of the tables in the document. Similar to TOC \location
M
\makebox Defines a box that has a specified width, independent from its content. See Boxes. \maketitle Causes the title page to be typeset, using information provided by commands such as \title{} and \author{}. \markboth \markright \mathcal \mathop
Command Glossary \mbox Write a text in roman font inside a math part \medskip \multicolumn \multiput
500
N
\newcommand Defines a new command. See New Commands. \newcolumntype Defines a new type of column to be used with tables. See Tables. \newcounter \newenvironment Defines a new environment. See New Environments. \newfont \newlength \newline Ends current line and starts a new one. See Page Layout. \newpage Ends current page and starts a new one. See Page Layout. \newsavebox \newtheorem \nocite Adds a reference to the bibliography without an inline citation. \nocite{*} causes all entries in a bibtex database to be added to the bibliography. \noindent \nolinebreak \nonfrenchspacing Setting the command untoggles the command \frenchspacing and activates LaTeX standards to insert more space after a period (.) than after an ordinary character. \normalsize Sets default font size. See Text Formatting. \nopagebreak Suggests LaTeX not to break page in this place. See Page Layout. \not
Command Glossary
501
O
\onecolumn \opening Inserts an opening phrase when using the letter class, for example \opening{Dear Sir} \oval \overbrace Draws a brace over the argument. Can be used in displaystyle with superscript to label formulae. See Advanced Mathematics. \overline Draws a line over the argument.
P
\pagebreak Suggests LaTeX breaking page in this place. See Page Layout. \pagenumbering Defines the type of characters used for the page numbers. Options : arabic, roman, Roman, alph, Alph, gobble (invisible). \pageref Used to reference to number of page where a previously declared \label is located. See Floats, Figures and Captions. \pagestyle See Page Layout. \par Starts a new paragraph \paragraph Starts a new paragraph. See Document Structure. \parbox Defines a box whose contents are created in paragraph mode. See Boxes. \parindent Normal paragraph indentation. See Lengths. \parskip \part Starts a new part of a book. See Document Structure. \protect \providecommand (LaTeX2e) See Macros. \put
Command Glossary
502
R
\raggedbottom Command used for top justified within other environments. \raggedleft Command used for right justified within other environments. \raggedright Command used for left justified within other environments. \raisebox Creates a box and raises its content. See LaTeX/Boxes. \ref Used to reference to number of previously declared \label. See Labels and Cross-referencing. \renewcommand \right \rm \roman \rule Creates a line of specified width and height. See LaTeX/Rules and Struts.
S
\savebox Makes a box and saves it in a named storage bin. \sbox The short form of \savebox with no optional arguments. \sc Small caps. \scriptsize Sets font size. See Text Formatting. \section Starts a new section. See Document Structure. \setcounter \setlength \settowidth \sf Sans serif. \shortstack \signature In the Letter class, specifies a signature for later insertion by \closing. \sl Slanted.
Command Glossary \slash See slash marks \small Sets font size. See Text Formatting. \smallskip \sout Strikes out text. Requires ulem package. See Text Formatting. \space force ordinary space \sqrt Creates a root (default square, but magnitude can be given as an optional parameter). \stackrel Takes two arguments and stacks the first on top of the second. \stepcounter Increase the counter. \subparagraph Starts a new subparagraph. See Document Structure. \subsection Starts a new subsection. See Document Structure. \subsubsection Starts a new sub-subsection. See Document Structure.
503
T
\tableofcontents Inserts a table of contents (based on section headings) at the point where the command appears. \telephone In the letter class, specifies the sender's telephone number. \TeX Prints TeX logo. See Text Formatting. \textbf{} Sets bold font style. See Text Formatting. \textcolor{}{} Creates colored text. See Entering colored text. \textit{} Sets italic font style. See Text Formatting. \textmd{} Sets medium weight of a font. See Text Formatting. \textnormal{} Sets normal font. See Text Formatting. \textrm{}
Command Glossary Sets roman font family. See Text Formatting. \textsc{} Sets font style to small caps. See Text Formatting. \textsf{} Sets sans serif font family. See Text Formatting. \textsl{} Sets slanted font style. See Text Formatting. \texttt{} Sets typewriter font family. See Text Formatting. \textup{} Sets upright shape of a font. See Text Formatting. \textwidth \textheight \thanks \thispagestyle \tiny Sets font size. See Text Formatting. \title \today Writes current day. See Text Formatting. \tt \twocolumn \typeout \typein
504
U
\uline Underlines text. Requires ulem package. See Formatting. \underbrace \underline \unitlength \usebox \usecounter \uwave Creates wavy underline. Requires ulem package. See Formatting.
Command Glossary
505
V
\value \vbox{text} Encloses a paragraph's text to prevent it from running over a page break \vcenter \vdots Creates vertical dots. See Mathematics. \vector \verb Creates inline verbatim text. See Formatting. \vfill \vline \vphantom \vspace This page uses material from Dr. Sheldon Green's Hypertext Help with LaTeX [1].
References
[1] http:/ / www. giss. nasa. gov/ tools/ latex/
506
507
508
509
510
511
512
License
513
License
Creative Commons Attribution-Share Alike 3.0 Unported //creativecommons.org/licenses/by-sa/3.0/