latex made easy

Upload: hoanbq

Post on 08-Apr-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 LaTeX made easy

    1/15

    Latest News Podcast Features Dis tros Code Apps Web Hardware

    Search

    LaTeX made easyPosted at 8:52pm on Friday April 3rd 2009

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

    This article will cover the

    basics, but you can do moreor less anything else youhave a mind to - although it'seasy to leave Latex to do theheavy lifting for you, there'salso scope to control yourformatting more closely if youprefer. If you've already readMythTV made easy, LTSPmade easy and Nagiosmade easy, read on to see

    what you can do with Latex...

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

    Listen to this: our Linux podcast kicks ass . Subscribe for free!

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    1 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    2/15

    The basic idea underlying Tex and Latex is that authors of a documentshould be concentrating on the s tructure of their work and leave thepresentation to designers, or in this case to the designer(s) of thetypesetting processor. So instead of choos ing fonts and decoration of textdirectly, you just identify it as a certain type of text (heading, lis t, diagram withcaption etc) and Latex will do the rest for you. It's incredibly powerful onceyou get started.

    Part 1: Latex basicsLet's look at a very bas ic sam ple 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{docum ent}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 notappear 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 \datecomm ands in the preamble. After that you get the text.

    Two newlines s ignify a new paragraph; otherwise whitespace is ignored, soyou can format things however it will make it easiest for you to navigate yoursource 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 havea % symbol at the start and are also ignored. You should have noticed thatLatex commands are all preceded by \. Some have arguments, which goeither in curly brackets (for obligatory arguments) or square brackets (foroptional arguments).

    There are two ways to turn this into a document, both of which are run fromthe CLI. The standard command is latex file.tex, which will produce a DVI

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    2 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    3/15

    file, file.dvi, which you can check out with the viewer of your choice (Evince isgood). Alternatively, you can use pdflatex file.tex to produce a PDF. Thecomm and-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 aprompt. Unfortunately Latex error mess ages can be a little obscure, but theline 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 miss ing \end{something}command, or misspelled commands ("Undefined control sequence").

    You may also see the warning "Overfull [or underfull] hbox" - this means thata particular line can't be squashed or s tretched enough to fill the linecorrectly. Don't worry about this unless you're at final version s tage, andeven then, eyeball the page before you decide to do anything. If it really doeslook bad, you can force hyphenation in a particular word.

    Output from an error-free Latex first run

    Part 2: FormattingSo, that's your first bas ic document. But you're going to want moreformatting 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. Everythingin the code snippets given here wil l 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

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    3 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    4/15

    sure you're aware is good practice to avoid people's eyes (not to mentionbrains ) 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 s tyles for yoursections, as per the screenshot below. If you use the commands as above,the sections will be num bered. To avoid using numbers, use \section*{} (\subsection*{} etc) - I use this as default.

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    4 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    5/15

    Section and sub-sec tion 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 saveit and re-run latex file.tex before reloading it in your viewer. You can alsocreate lis ts, both ordered and unordered, as per the code sample, andcreate definition lists, which have a slightly different structure. They're a bitlike a dictionary type list, where you provide a header and then anexplanation. Compare the code here with the screenshot, below, to seewhat'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 anenvironment.) This bas ically means that they influence a larger section ofyour document than a non-environment command does. Latex can handleother commands , including nested environments, within environments.

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    5 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    6/15

    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 multipleparagraphs), or the \begin{verse} ... \end{verse} environment for poetry (itenables you to indicate newlines with \\).

    The quotation environments wil l all indent the included text from the maintext 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}.

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    6 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    7/15

    ParagraphsLatex treats an empty line as indicating a paragraph break, but this doesn'tmean that you get a blank line between paragraphs in your output file -books don't do this (they use indents ins tead), so Latex by default doesn'teither. However, this behaviour can be customised. If you want 1cmbetween paragraphs , put the following line in your preamble (not in themain 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 noparagraph indents and no paragraph spacing, it won't be clear where yourparagraphs 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 i f I'm going to bemessing around with font size, because they will change along with the fontsize.

    Part 3: PicturesSometimes, words alone will not suffice, which is why LXF is bles sed withpretty pictures. Latex supports adding pictures, although unfortunately theprocess 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 ins tallation.

    A quick note here on packages . Packages are a way of extending the basic

    Latex commands. You can define your own commands and package themyourself, if you fancy a little wheel-reinvention, or you can use the numerouspackages that other people have already created, most of which areavailable via CTAN (the Comprehens ive Tex Archive Network). Once you'veput the package up in the preamble, you can access the commands fromthat 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

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    7 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    8/15

    environment tells Latex to treat everything ins ide it as a s ingle block,separate from the rest of the surrounding text. The processor will work outthe size of your figure, then place it as close as poss ible to the place whereit's referenced in the text, while also fitting it in somewhere sens ible in thedocument flow. This does mean that you can't decide where exactly to putyour figure - you have to rely on Latex doing that for you. Relax and acceptthe loss of control...

    However, if you really can't relax, or if you have a very figure-heavy documentwhich 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, orhere (h) - that is, where the figure is in the source code. A more emphaticway of doing this is to use [tbh!], but you should in general be OK just lettingLatex do its thing.

    You include the picture itself with the \includegraphics command. It needs tobe in EPS (Encapsulated PostScript) format (this would be one of thesources of mild nuisance al luded to at the s tart of this section). Gimp willgenerate EPS files for you from your JPG or PNG files , but they may not begreat quality; Inkscape, OpenOffice.org Draw or another vector editorprogram may be better bets. EPS files are pretty much self-contained,making them much eas ier to place inside another PS (or PDF) document,which is why they're used here.

    Roll your own

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

    \usepackage{xspace}

    \newcommand{\lf}{Linux Format}

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

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

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    8 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    9/15

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

    More than wordsFinally, you get to give the picture an appropriate caption, and you shouldinclude a label in the caption. The label means that you can refer to thepicture in your text, and Latex will automatically generate a number (egFigure 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 thereferences correct - on the first run you'll get a warning about undefinedreferences.

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

    Changing the marginsThe default Latex margins are very large. Donald E Knuth had abig thing about length of lines, pointing out that books have onlyfairly 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 thepreamble):

    \usepackage{setspace}

    \setlength{\parskip}{1ex}

    \setlength{\topmargin}{0in}

    \setlength{\oddsidemargin}{0in}\setlength{\evensidemargin}{0in}

    \setlength{\textheight}{9in}

    \setlength{\textwidth}{6.25in}

    \setlength{\headwidth}{6.25in}

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    9 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    10/15

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

    Part 4: Document typesSo far, everything we've looked at has been in the context of the articledocument type. we set this right at the top of the sample document, in theline:

    \documentclass{article}

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    10 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    11/15

    Before we look at other types of document, note that the \documentclassargument 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 optionsavailable as well: twoside, twocolumn, draft (this marks over-long lines witha little marginal squiggle, and doesn't print pictures in full, instead showingonly 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), andlandscape.

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

    article This is useful for mos t things.report Enables you to have several chapters.book Can handle chapters, table of contents, and generally tome-likethings.letterUnsurprisingly, good for writing letters.All of these work in a fairly similar way, but have different defaults. Forexample, article doesn't create a new page for the title by default, whilereport and book do. (Although you can change this by putting titlepageor notitlepage as an option in the \documentclass argument. Latexreal ly is very flexible!)

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

    \documentclass{letter}

    \signature{Juliet Kemp}

    \address{My House \\ London }

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

    Please do get in touch.

    \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 onthe correct sides of the page, will format the letter appropriately, and

    will add the PS and enclosure notes after the closing (which uses yourname as set in the preamble). You can put multiple letters (eachenclosed in a \begin{letter}...\end{letter} environment) in a singledocument, which saves you having to put your name and address inevery time if you're writing a big s tack of letters (that bridge ain't goingto sell itself, after al l...).

    Latex may initially seem a little awkward to write with, but you get used

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    11 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    12/15

    to it very quickly (particularly if you set up editor shortcuts). And I hopeyou'll find that the flexibil ity and ease of layout you gain from it is wellworth the learning curve - even if control geeks end up bullying you intospelling it LaTeX!

    Going furtherLatex has many other exciting options. It handles mathsand equations particularly well, courtesy of the built-inmaths mode.

    Bibtex (which comes by default with a standard Latexinstall) is a bibliography-handling system which is veryuseful if you're doing anything which utilises citations.CTAN, the Comprehensive Tex Archive Network(www.ctan.org) has an enormous directory of Texpackages available for download. There are packages for

    working with fonts, graphics, languages, indices, andassorted other bits and bobs, making it well worth abrowse even if you're jus t curious .

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

    First published in Linux Format magazine

    You should follow us on Identi.ca orTwitter

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    12 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    13/15

    Your comments

    LaTeX Editorkdnewton (not verified) - April 4, 2009 @ 3:27am

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

    TeXmakerMorten Juhl-Johansen Zlde-Fejr (m jjzf) (not verified) - April 16, 2009 @ 12:44pm

    I used TeXmaker - pretty much the same as Kile, but only QT4-based. Still, I alsoliked working with LyX for semi-WYSIWYG editing. I found TeXmacs annoying, but Igreatly respect their philosophy that a mathematical result or proof achieved withthe aid of a computer can only be accepted if the application is open source:

    http://www.texmacs.org/tmweb/about/philosophy.en.html

    Thanks!!Stan (not verified) - July 22, 2009 @ 2:28am

    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 onTuxRadar like this, because it starts off jus t right and keeps the reader interested

    and trying new things . :)

    Keep up the good work!!

    another vote for hardware compatibility/rev iewsAnonymous Penguin (not verified) - July 26, 2009 @ 8:43am

    perhaps as a half page spread on the backpage with (as noted in the letterssection of the latest issue) the anatomy of a geek desktop resurrected (!), orperhaps 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 beuseful...

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    13 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    14/15

    Copyright 2010 Future Publishing Limi ted (company

    registered number 2008885), a company registered in

    Post new comment

    Your name:

    Anonymous Penguin

    Title:

    Comment: *

    CAPTCHA

    Fill in this captcha, or you shall be mocked mercilessly.

    Preview comment Post comment

    Username: Passw ord: Log in

    Create Account | About TuxRadar

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    14 of 15 02/21/2011 05:28 P

  • 8/7/2019 LaTeX made easy

    15/15

    Engl and a nd Wales whose registered offic e i s at Beauford

    Court, 30 Monmouth Street, Bath, BA1 2BW, UK

    Terms & Conditions | Privacy Policy

    Web hosting by UKFast

    LaT eX made easy | T uxRadar Linux http://www.tuxradar.com/content/latex-made-ea

    15 of 15 02/21/2011 05:28 P