OpenOffice.org and other word processors do a perfectly decent job for basic text, but sometimes you want better typesetting than that. LaTeX (pronounced "lay-tech" and commonly written Latex much to the annoyance of geek pedants) may look formidable, but once you get into the swing of it, it's remarkably straightforward, and manages to give you excellent control over how your deathless prose appears on the page without undue fuss.

This article will cover the basics, but you can do more or less anything else you have a mind to - although it's easy to leave Latex to do the heavy lifting for you, there's also scope to control your formatting more closely if you prefer. If you've already read MythTV made easy, LTSP made easy and Nagios made easy, read on to see what you can do with Latex...

Latex is a document markup language and preparation system, which uses the TeX (pronounced "tek", commonly written "Tex") typesetting language written by Donald E Knuth. Tex is very low-level and using it directly would be no fun at all for most of us; Latex gives a more human-friendly way to access it.

The basic idea underlying Tex and Latex is that authors of a document should be concentrating on the structure of their work and leave the presentation to designers, or in this case to the designer(s) of the typesetting processor. So instead of choosing fonts and decoration of text directly, you just identify it as a certain type of text (heading, list, diagram with caption etc) and Latex will do the rest for you. It's incredibly powerful once you get started.

## Part 1: Latex basics

Let's look at a very basic sample Latex document.

\documentclass{article}
\title{A basic Latex document}
\author{Juliet Kemp}
\date{June 2008}
\begin{document}
\maketitle
Latex (pronounced lay-tech) is a document markup language and preparation
system, which uses the Tex typesetting language written by Donald E
Knuth. Tex is very low-level; Latex gives a more human-friendly way of
accessing it.
This is a second paragraph.
% This is a comment line which won't be typeset.
\end{document}
And this line here won't be typeset either.


So: first up is the preamble section - the part before the \begin{document} line. This is where you put the document type (in this case, an article), author, and date. The preamble is just setup information, and will not appear on the page. The body of the document - the stuff that you want to actually appear on the page - goes between the \begin{document} and \end{document} lines.

The \maketitle command generates the title from the \title, \author, and \date commands in the preamble. After that you get the text.

Two newlines signify a new paragraph; otherwise whitespace is ignored, so you can format things however it will make it easiest for you to navigate your source document. And if you put something outside the document section (as in the code example), it won't be typeset.

This can be useful for writing notes to yourself with no risk that they'll show up in the finished article when you forget to remove them... Comments have a % symbol at the start and are also ignored. You should have noticed that Latex commands are all preceded by \. Some have arguments, which go either in curly brackets (for obligatory arguments) or square brackets (for optional arguments).

There are two ways to turn this into a document, both of which are run from the CLI. The standard command is latex file.tex, which will produce a DVI file, file.dvi, which you can check out with the viewer of your choice (Evince is good). Alternatively, you can use pdflatex file.tex to produce a PDF. The command-line output of latex file.tex is shown in the screenshot below.

If you get any errors in the output (they'll begin with !), hit X to get back to a prompt. Unfortunately Latex error messages can be a little obscure, but the line number gives you an area to start looking for problems. Common problems include missing opening or closing brackets on a command ("Too many }'s" or "Runaway argument"), a missing \end{something} command, or misspelled commands ("Undefined control sequence").

You may also see the warning "Overfull [or underfull] hbox" - this means that a particular line can't be squashed or stretched enough to fill the line correctly. Don't worry about this unless you're at final version stage, and even then, eyeball the page before you decide to do anything. If it really does look bad, you can force hyphenation in a particular word.

Output from an error-free Latex first run

## Part 2: Formatting

So, that's your first basic document. But you're going to want more formatting than that, so let's look at other things you can do. From here on, you should edit the document that you produced in the first part. Everything in the code snippets given here will go in the document body, between the \begin{document} and \end{document} tags, unless stated otherwise.

One useful option is to divide your document into sections, which as I'm sure you're aware is good practice to avoid people's eyes (not to mention brains) getting bored. For example:

\section{Latex Formatting}
There are different types of formatting available.
\subsection{Sections}
Like sections.
\subsubsection{Also sub-sub-sections}
There's a whole hierarchy going on here. It does have a limit, though.


Latex will then automatically produce appropriate heading styles for your sections, as per the screenshot below. If you use the commands as above, the sections will be numbered. To avoid using numbers, use \section*{} ( \subsection*{} etc) - I use this as default.

Section and sub-section headings - notice how the font size decreases the further down the hierarchy you go.

Remember that every time you edit your source code file, you'll need to save it and re-run latex file.tex before reloading it in your viewer. You can also create lists, both ordered and unordered, as per the code sample, and create definition lists, which have a slightly different structure. They're a bit like a dictionary type list, where you provide a header and then an explanation. Compare the code here with the screenshot, below, to see what's going on.

\begin{itemize}
\item These list items
\item Will show up
\item With bullets.
\end{itemize}
\begin{enumerate}
\item These list items
\item Will show up
\item With numbers.
\end{enumerate}
\begin{description}
\item[LaTeX] Latex is the language.
\item[command] Commands structure what you can do with Latex.
\item[Package] Packages allow you to add extra commands.
\end{description}


Lists are environments - commands that are structured as \begin{something} . . . \end{something}. (The document itself is therefore an environment.) This basically means that they influence a larger section of your document than a non-environment command does. Latex can handle other commands, including nested environments, within environments.

You can get bulleted and numbered lists, as well as the less common dictionary-style description lists.

Quotation environments are also available, using the \begin{quote} ... \end{quote} environment for short quotes, the \begin{quotation} ... \end{quotation} environment for longer quotes (it deals better with multiple paragraphs), or the \begin{verse} ... \end{verse} environment for poetry (it enables you to indicate newlines with \\).

The quotation environments will all indent the included text from the main text body. The whole point of Latex is to go easy on the explicit formatting - let the program do the work. But sometimes you want italics - try \emph{italics}. Or bold type - \textbf{bold face}. Or Courier-style text - \texttt{like this}.

### Paragraphs

Latex treats an empty line as indicating a paragraph break, but this doesn't mean that you get a blank line between paragraphs in your output file - books don't do this (they use indents instead), so Latex by default doesn't either. However, this behaviour can be customised. If you want 1cm between paragraphs, put the following line in your preamble (not in the main document environment!):

\setlength{\parskip}{1cm}
You can also alter the paragraph indent, with:
\setlength{\parindent}{1cm}


To turn it off entirely, use a zero value, but be warned that if you have no paragraph indents and no paragraph spacing, it won't be clear where your paragraphs are!

Latex takes measurements in cm, mm, inches, ex (the height of a typeset x), em (the width of a typeset M), points and bp (big points, which are very slightly larger than a regular point). I quite like ex and em if I'm going to be messing around with font size, because they will change along with the font size.

## Part 3: Pictures

Sometimes, words alone will not suffice, which is why LXF is blessed with pretty pictures. Latex supports adding pictures, although unfortunately the process can be a bit of a nuisance.

What you'll end up with in your Latex source will look a bit like this:

% This line goes in the preamble section
\usepackage{graphicx}
% These lines go in the main document body
\begin{figure}
\includegraphics{tree.eps}
\caption{\label{tree}This is a particularly nice tree.}
\end{figure}


First, you need to include the graphicx package, which will do the picture-wrangling for you. This should be standard in your Latex installation.

A quick note here on packages. Packages are a way of extending the basic Latex commands. You can define your own commands and package them yourself, if you fancy a little wheel-reinvention, or you can use the numerous packages that other people have already created, most of which are available via CTAN (the Comprehensive Tex Archive Network). Once you've put the package up in the preamble, you can access the commands from that package in the rest of the document. It's dead easy.

OK, back to adding our picture. In the body of the document, the figure environment tells Latex to treat everything inside it as a single block, separate from the rest of the surrounding text. The processor will work out the size of your figure, then place it as close as possible to the place where it's referenced in the text, while also fitting it in somewhere sensible in the document flow. This does mean that you can't decide where exactly to put your figure - you have to rely on Latex doing that for you. Relax and accept the loss of control...

However, if you really can't relax, or if you have a very figure-heavy document which confuses Latex, you can add [tbh] to the figure environment, like this:

\begin{figure}[tbh]


This tells Latex to place the figure at the top (t) or bottom (b) of a page, or here (h) - that is, where the figure is in the source code. A more emphatic way of doing this is to use [tbh!], but you should in general be OK just letting Latex do its thing.

You include the picture itself with the \includegraphics command. It needs to be in EPS (Encapsulated PostScript) format (this would be one of the sources of mild nuisance alluded to at the start of this section). Gimp will generate EPS files for you from your JPG or PNG files, but they may not be great quality; Inkscape, OpenOffice.org Draw or another vector editor program may be better bets. EPS files are pretty much self-contained, making them much easier to place inside another PS (or PDF) document, which is why they're used here.

Being as it is an actual language (although I'm not sure if it's Turing-complete!), Latex allows you to define your own macros (commands) using \newcommand. This can be useful if you have a complicated name or sentence to write repeatedly. For example, you could set up this:

\usepackage{xspace}
\newcommand{\lf}{Linux Format}


in your preamble. Thereafter, whenever you want to type 'Linux Format' in the body of your document, you can instead type \lf.

The xspace package is used here because by default, Latex treats whitespace after a command as indicating the end of the command, not as actual whitespace. So if you typed 'I read \lf regularly.', it would come out as 'I read Linux Formatregularly.' (note the lack of space between the last two words) The xspace package fixes this problem and should be included in a standard install.

Macros are particularly useful if you're doing complicated maths - you can type the formula once only, in the macro definition, and use something easier to remember thereafter. You can also add arguments to the command. If you want to redefine an existing Latex command, you can do use \renewcommand in the same way.

### More than words

Finally, you get to give the picture an appropriate caption, and you should include a label in the caption. The label means that you can refer to the picture in your text, and Latex will automatically generate a number (eg Figure 1.1) for the picture, and a correctly numbered reference to it. References within the main document text look like this:

The picture at Figure \ref{tree} shows how very useful this all is.


Note that you need to run the latex file.tex command twice to get the references correct - on the first run you'll get a warning about undefined references.

If you've ever decided to insert another figure, graph, or photo into a document, and then spent the next 10 minutes swearing and altering all the numbering and references by hand, you will appreciate this degree of automation immensely. If you haven't done this before, please feel free to go and do so now in order to increase your appreciation of Latex.

## Changing the margins

The default Latex margins are very large. Donald E Knuth had a big thing about length of lines, pointing out that books have only fairly short lines to make them easier on the eye when reading. You may well wish to reduce these margins a bit to save paper. The settings I tend to use look like this (all this goes in the preamble):

\usepackage{setspace}
\setlength{\parskip}{1ex}
\setlength{\topmargin}{0in}
\setlength{\oddsidemargin}{0in}
\setlength{\evensidemargin}{0in}
\setlength{\textheight}{9in}
\setlength{\textwidth}{6.25in}


An example Latex document - note the header and very wide margins!

## Part 4: Document types

So far, everything we've looked at has been in the context of the article document type. we set this right at the top of the sample document, in the line:

\documentclass{article}


Before we look at other types of document, note that the \documentclass argument can take various options. For example, \documentclass[a4paper,11pt]{article} will set your document to use, surprisingly enough, A4 size paper and 11pt font. There are other options available as well: twoside, twocolumn, draft (this marks over-long lines with a little marginal squiggle, and doesn't print pictures in full, instead showing only an empty box), leqno/reqno (which specify that equation numbers should go on the left of the page or the right of the page respectively), and landscape.

You can also set up different types of document. The main types are as follows:

• article This is useful for most things.
• report Enables you to have several chapters.
• letter Unsurprisingly, good for writing letters.
• All of these work in a fairly similar way, but have different defaults. For example, article doesn't create a new page for the title by default, while report and book do. (Although you can change this by putting titlepage or notitlepage as an option in the \documentclass argument. Latex really is very flexible!)

Let's take a quick look here at using the letter class.

\documentclass{letter}
\signature{Juliet Kemp}
\begin{document}
\begin{letter}{Ms Smith \\ Their House \\ London }
\opening{Dear Ms Smith,}
I wondered if you might be interested in a bridge I have to sell. Light use,
one careful owner, all offers will be considered.
\closing{Yours sincerely,}
\ps{P.S. I have enclosed the particulars of the bridge. As you can see, it
goes all the way over the river at both ends.}
\encl{enclosure.txt}
\end{letter}
\end{document}


Latex will generate the addresses (and today's date) automatically on the correct sides of the page, will format the letter appropriately, and will add the PS and enclosure notes after the closing (which uses your name as set in the preamble). You can put multiple letters (each enclosed in a \begin{letter}...\end{letter} environment) in a single document, which saves you having to put your name and address in every time if you're writing a big stack of letters (that bridge ain't going to sell itself, after all...).

Latex may initially seem a little awkward to write with, but you get used to it very quickly (particularly if you set up editor shortcuts). And I hope you'll find that the flexibility and ease of layout you gain from it is well worth the learning curve - even if control geeks end up bullying you into spelling it LaTeX!

## Going further

Latex has many other exciting options. It handles maths and equations particularly well, courtesy of the built-in maths mode.

Bibtex (which comes by default with a standard Latex install) is a bibliography-handling system which is very useful if you're doing anything which utilises citations. CTAN, the Comprehensive Tex Archive Network (www.ctan.org) has an enormous directory of Tex packages available for download. There are packages for working with fonts, graphics, languages, indices, and assorted other bits and bobs, making it well worth a browse even if you're just curious.

Of course, if you can't find anything that does exactly what you're after, you can create your own packages.

First published in Linux Format magazine

### LaTeX Editor

I like to use Kile as my LaTeX editor of choice. It's got buttons to easiyl compile the source direct to PS or PDF. It will give warnings for errors as well.

### Thanks!!

Thank you very much for making this (though I may just be a year late ;) .)!!

Too often tutorials are made without being brief and introductory. I love articles on TuxRadar like this, because it starts off just right and keeps the reader interested and trying new things. :)

Keep up the good work!!

### another vote for hardware compatibility/reviews

perhaps as a half page spread on the backpage with (as noted in the letters section of the latest issue) the anatomy of a geek desktop resurrected (!), or perhaps in the form of the book reviews section so could cover a few things an issue...

In particular, a list of mobile phones that work successfully with linux would be useful...

### Thank you

I used Texmaker for the first time. Your explanation helped me produce an outstanding document. Many thanks!