6656

37
+85  Q:

## Best practices in LaTeX

What are some good practices when typesetting LaTeX documents?

I use LaTeX mostly to typeset papers. Here is a short list of what I consider LaTeX good practices, most of them would be common sense in any programming language:

• When writing a large document (book), keep the chapters in separate files
• Use a versioning system
• Repeated code (i.e. piece of formula occurring many times) is evil. Use macros
• Use macros to represent concepts, not to type less
• Use long, descriptive names for macros, labels, and bibliographic entries
%===================================
to emphasize the beginning of sections and subsections
• Comment out suppressed paragraphs, don't delete them yet
• Don't format formulas (i.e. break them into many lines) until the final font size and page format are decided
• Learn to use BibTeX

Further question: What package/macro/whatever do you use to insert source code?

+1  A:
• Lgrind is a good tool for rendering source code listings in LaTeX.
+46  A:

Put your files in source control. This makes it so you don't need to keep long comment blocks in as long.

It also can be helpful if you've written a large section that you decide to yank for the current publication, but that you'll want later (e.g. for a tech report or for a journal paper). Subversion-style tags can be especially helpful at times like this.

I can vouch for that. I actually use Eclipse to manage my text files and diffs, though I edit with WinEDT and TeXShop
Source control would have saved me a ton of time. I had a laptop crash in the middle of writing my thesis. I didn't know anything about source control in those days. I'd give more points if I could.
@Anthony: that's not about source control. That's about having backups (and a recovery plan)
+8  A:

Might seem too obvious, but it's vitally important to use a good editor that:

• Makes things like inserting commonly used macros/comment markers/latex tags easy and consistent.
• Can highlight the source properly
• Can format the source properly

Either (g)Vim or emacs can do all of these, but I'm sure there will be plenty of others.

Eclipse has a plugin for latex syntax highlighting as well
kile and texnicenter are good editors IMHO
+23  A:

Use a Makefile, or some other kind of build script to build your document from your sources. This may include generating plots or other graphics outside of the latex system. This becomes even more important if you need to rebuild the document from source at some later date (for example, you need to regenerate a paper with new data).

latexmk is handy in this regard for the latex/bibtex side of things (see my answer below).
A nice ready makefile is the "The Ultimate Latex Makefile", see below =)
I have tried both those solutions, during the course of my thesis and neither can deal with a complex document fully. I just use a simple Makefile which deals with converting all my figures etc and runs (pdf)latex once. It's not too hard to bibtex/makeindex/repeat latex myself.
Scons can do that, to me it seems even more simple than a Makefile.
After trying several kinds of super-complex makefiles, I discovered [rubber](http://www.pps.jussieu.fr/~beffara/soft/rubber/) and never looked back.
+4  A:

Be sure you are clear about what page format, letter or A4, you are generating.

+27  A:

I could probably go on all day, but this seems like a good start.

# if you want to change the page margins:
\usepackage[letterpaper]{geometry}
\geometry{top=1.0in, bottom=1.0in, left=1.5in, right=1.0in}

# greatly improved citation commands:
\usepackage[longnamesfirst]{natbib}

# better looking tables with \toprule,\midrule,\bottomrule:
\usepackage{booktabs}

# make sure figures do not appear before their text:
\usepackage{flafter}

# if you're doing math:
\usepackage{amsmath,amssymb,cancel,units}

# more control with verbatim ('unformated') environments:
\usepackage{fancyvrb}
I advise against the first point: setting the margins by hand is not something you should routinely do. The default document classes have the margins that respect document setting best practices. If you change them, you should either know those best practices, or be aware that you most likely deviate from best practices.
That’s a fair point. I included that block as an example of the easiest way to change the page margins, not because I think those are the best possible margins. But I can see where this might not be clear.
Can you provide links to the documentation of those packages? You've given their names, but not what exactly they contain that is useful.
+6  A:

I like your list but I don't know if I agree with

Repeated code (i.e. piece of formula occurring many times) is evil

For someone comfortable enough with LaTeX, reading the LaTeX should be like reading the paper (obviously this is never completely true). If the repeated code is an eyesore for the LaTeX reader then it is probably also an eyesore for the reader of the pdf document.

Certainly there are exceptions where the LateX is cumbersome but the output is simple and in this case you should use a macro. But perhaps when you are tired of writing part of a formula over and over again you should consider that your reader may also be tired of reading it over and over again.

So I might replace this point with

Try to keep the structure of your code similar to the structure of your document

I'm not speaking about text. Mostly, I meant formulas. Suppose there's a quantity named 't_f' in your 123 formulas, say "final time". Now you decide that 'T_f' would be better... You got the idea. It's not merely a matter of search/replace...
+6  A:

Spelling the name correctly is a good practice: LaTeX

("Latex" is a sort of allergenic rubber.)

(I'm not just being snarky ... when I first saw the title of this post, I thought, 'what strange new scripting language is 'latex'? The traditional capitalization does carry meaning.)

By the way, someone answered "lots of margarine on your legs". My fault.
*coffee in my nose from laughing* ... *ow* ...
@Eric: There are some, who on the other hand, *hate* the practice. Robert Bringhurst, in *Elements of Typographic Style* for example, says that with TeX, Knuth opened a can of worms, with everyone coming up with weird kerning for names like LaTeX, AMSTex, LaTeX2e, ..., which is a visual assault. In his opinion, type should be just that, free of "logos". I can see his point. I am not sure if I agree with it yet. :-)
+9  A:

I use the KOMA-script package for all my documents. It provides counterparts or replacements for the standard LaTeX classes such as article, book, etc., but offers many additional features and its own unique look and feel.

The KOMA-Script bundle provides drop-in replacements for the article/report/book classes with emphasis on typography and versatility. There is also a letter class, different from all other letter classes. It also offers e.g. a package for calculated type areas in the way laid down by the typographer Jan Tschichold, a package for easily changing and defining of page styles, a package for getting not only the current date but also the name of day and a package for getting current time. All these packages may be used not only with KOMA-Script classes but also with standard classes. (Source)

+36  A:

Use the fact that LaTeX is not WYSIWYG. When writing paragraphs, start each sentence at the beginning of a line, and if it spills over, each subsequent line is tabbed.

This helps you understand the structure of your paragraphs and identify materials in them very fast.

I've since written many documents with this practice and it was always effective.

Good tip. I also use the new line for new sentence approach but hadn't thought to indent the spill-over.
I indent my latex-document for logical structure (like I do in programming). I keep long lines long, my editor makes linebreaks by keeping the intendation. And paragraphs are easy to see, because latex wants a linebreak for them.
Good tip. Actually, keeping one sentence per line helps when using VCS. For that reason now I prefer not to wrap the lines.
I don't suppose you have a emacs mode or macro to set this up?
It doesn't require a macro. Just a creative use of the tab key. If you use WinEDT or TexSHOP, just try it out, if you are in mid-sentence when you get to a newline, just add a tab before you go on typing. It won't shop up in the rendered version, just the Tex
One line per sentence is nice, because it reduces the probability of conflicts when several authors collaborate via a VCS. It's not so nice when your colleagues don't care about formatting and soft-wrap whole paragraphs :)
That's a very good point. I didn't have that issue because of how we were working (over the final PDFs) but this tip would indeed be problematic if you rely on line level comparisons.
Starting each sentence on a new line is very helpful, as it makes it easier to understand differences between two source files using standard diff tools (e.g. when comparing different versions saved in a version control system). Changes to one sentence don't produce trivial differences due to changes in the line wrapping for the rest of the paragraph.
+4  A:

I am using LaTeX mostly for typesetting software manuals for our customers. I use macros for the name of the company and some other things that appear often in the document. Besides saving myself a few seconds here and there, it has the advantage that you can easily change the customers name if you use the same text for another customer - it makes for easier abstraction.

Apart from that, I recommend modularisation. The 'main' file contains the definitions that are only specific to this document and the chapter structure. Put each chapter in its own file, but also have a seperate file with all the page layout etc. I have several layout templates and can easily switch between them. This would also be valid for research papers - many publishers require their own layout.

Why do you disagree?! Yours is *exactly* an example of what I mean by "representing concepts"! I use macro for pieces of formulas, you use them for company names.
Perhaps I should change the word "concept"? "thing"? "object"? Please suggest...
Uff... I see your point. For me, 'to type less' was exactly why I started using my own macros (yes, I am a lazy person ;-) If you like, you can rephrase it as 'Use macros for better abstraction'. Sounds very abstract, though... Lets just say I misunderstood you, and revoke my disagreement
+18  A:

This may not be the type of tip you are after but if you haven't already,take a look at LyX. It's an open-source word processor-like front end for LaTeX with lots of features built-in (version control, comments), very configurable and a good community.

I wrote my PhD thesis (all 220 1.5-spaced pages of it!) in LyX and found it much easier than straight LaTeX (I did my maths honours thesis in emacs + LaTeX). It's especially good at helping manage figures, tables and other fiddly environments. You can drop into straight LaTeX anytime you want and see a live preview of maths and graphics as you type.

I still use LaTeX (and TextMate) when collaborating with other LaTeX-only users but if I'm writing something by myself, LyX is my first choice.

+1 for Lyx. It gave me hand cramps personally (the version I used has terrible UI) but it's a good way to ease into LaTeX
If you want realtime LaTeX I would suggest Bakoma Tex instead - it is far more powerful and convenient.
+15  A:

My top suggestion is to format LaTeX source the same way you would format source code as far as indention, lining up opening and closing braces, etc. People tend to put all the LaTeX source for an equation on one line, even though it may have 10 nested pairs of opening and closing groupings, and even if they'd never do anything like that in C. The most effective technique I know for debugging errors in LaTeX files is to simply format the source like I would C++ code. For example

$x = \frac { -b \pm \sqrt{ b^2 - 4ac } } { 2a }$

I put all the square root stuff on one line only because it's very short. But especially for the \frac command, extra white space really helps.

From LaTeX FAQ: While the double dollar sign (still) works in LaTeX, it is not part of the "official" LaTeX command set (in fact, most books on LaTeX don't even mention it) and its use is discouraged. Use the bracket pair "$", "$" instead.)
(Of course, I still use $$since that is what I learned so many years ago...) I agree with formatting code, but I disagree with C++ style. ;) I see that formatting like C code also multiplies the denominator of the fraction with c... :-) I changed$$ to $and$. This notation is more consistent with my answer anyway, making beginnings and endings clearer. I also removed the c in the denominator per Daan's suggestion. :-)
+9  A:

This isn't exactly a best practice, but a possibility for LaTeX that not too many people know about. If you need to insert calculations in your LaTeX file, you can embed R code using Sweave. When you run Sweave, it produces a LaTeX file with the results of your calculations inserted in the file. Sweave embeds R inside LaTeX the way CGI, PHP, etc. embed script inside HTML.

With Sweave you can, for example, embed data and plotting commands in your LaTeX file. Then if you need to change the data, you don't need to manually create a new image and paste it in; Sweave recreates the image and embeds it for you. So your data and your plots stay in sync.

If you have any trouble getting started with Sweave, see troubleshooting Sweave.

+1  A:

First and foremost, I think the best practice is to have: A Guide to LATEX: Tools and Techniques for Computer Typesetting, by Helmut Kopka and Patrick W. Daly (Addison Wesley, 4th Edition, ISBN: 0321173856) nearby.

Once you find the preamble settings that work for whatever publication you are using, put them into their own preamble file. This will make finding the right settings a lot easier.

Moreover, if you find an environment setting you like, save it as well. For formatting code, I like:

\newenvironment{mylisting}
{\begin{list}{}{\setlength{\leftmargin}{1em}}\item\scriptsize\bfseries}
{\end{list}}

I happened to like WinEdt as an editor. Since at the time I wasn't as computer saavy as I am now, it made rendering my files a lot easier. Because of the text formatting and coloring it also made it easier to notice when something was not formatted correctly.

+7  A:
1. If possible use Emacs to edit LaTeX files, using RefTeX (for handling citations) and AucTeX. Some people also like preview-latex, for having an almost WYSIWYG experience: your mileage may vary on that.
2. Use the comment environment for commenting one paragraph or more, so that your version control sw does not complain
3. Beware of end-of-line control characters if your collaborators use different OS
4. Use a programmatic environment for producing graphics. Metapost is the oldest and stablest (it's also used by Knuth). Pstricks is probably the most resourceful, but it's a bit outdated. Tikz is the new kid on the block and already very good. I switched to tikz as it's able to deal with both postscript and pdf outputs.
5. Read a "not so short guide to latex2e", after that move to Kopka & Daly.
6. Have a look at the memoir package for designing a new document style: it's also a great guide to publishing.
7. I use listings for display source code. It's ok, but not something definitive: you can probably do fine with a simple verbatim environment (maybe with fancyvrb).
Yes, Tikz is indeed very good. I use it for the same reason.
+2  A:
+15  A:

I highly recommend the short math guide which includes explicit best practices for typesetting math using AMSLatex (built in to any LaTeX installation).

It's pretty amazing -- 17 pages and it's all I've ever needed to know about typesetting math.

Best Practices Excerpts:

• Don't use eqnarray as it "produces inconsistent spacing of the equal signs and make no attempt to prevent overprinting of the equation body and equation number."

• Use $math stuff$ instead of $$math stuff$$.

• Use \quad, \qquad, \phantom and other standard ways of inserting whitespace.

• Use \lvert and \rvert for absolute value.

• Check out \DeclareMathOperator.

• \begin{cases} for piecewise functions (like f(x) = 2 if x<7 or 3 otherwise).

• \dfrac and \tfrac for overriding LaTeX's guess about the size of fractions.

From the AMS web page:

This guide is a concise summary of the essential features in LaTeX for writing math formulas , including features provided by the packages amssymb and amsmath . This is not a mere listing of everything available but a careful selection of the LaTeX commands that are especially recommended for authors' use. There is also some discussion of certain common uses and misuses of various commands that are better avoided for reasons of typographical quality or logical markup.

+3  A:

Do this

\newcommand{\foo}{\ensuremath{stuff}}

rather than

\def\foo{stuff}

One advantage of the former is that you can then use \foo both in and out of math mode.

+17  A:

I created several unary commands to tag sections of text, such as \HighlightProblem, \ConsiderRemoving, \CollaborateWithCoauthor, etc. (I use acronyms, of course). These commands display the text in a different color.

When I watch the PDF, this helps me quickly see areas that need work.

In some cases, I use several "confidence level" tags, so that areas that are more "stable" appear in black or closer to black, while less stable areas appear in lighter grays.

Well, aren't we posh? I just have two variants on \fixme (the main one uses marginpars, the other is inline for captions and the like). Anyway. +1
I often need them since I deal with long documentations, and my advisor deals with them piecemeal.
You might try the todonotes package, which provides this sort of thing. Esp with the inline option.
Hehe, I like the lighter grays for less stable text parts.
+6  A:

I recommend latexmk which, with -pvc switch (for "preview continuously"), will recompile (as many times as necessary) whenever the source changes. If you have a pdf viewer that autorefreshes the pdf view (Skim on Mac OSX does this) then you can see a refreshed preview every time you hit save.

Using latexmk is nice even without the -pvc option since it automatically compiles (including bibtex) as many times as necessary.

(For most documents, latexmk obviates the need for a Makefile.)

See this question for a mini-tutorial on latexmk: http://stackoverflow.com/questions/738755/dont-make-me-man

Do I need latexmk for that when I have Skim?
Yes, Skim and latexmk are orthogonal. Skim is just a pdf viewer that autorefreshes when the pdf file changes on disk. latexmk continuously compiles your tex source into pdf when the tex source changes.
The default viewer "Preview" on Mac OS X also auto-refreshes the PDF. At least my version does (Preview 4.2 on Mac OS 10.5.8). As soon as you switch to the Preview window it will display the updated PDF.
Oh, maybe Preview has gotten smarter! Although it's actually important that it refresh even without you switching to it, so that you can see the updated pdf in real time without leaving your editor.
+2  A:

A nice Makefile for latex, finds the dependencies etc automatically (and quite nicely) : The Ultimate Latex Makefile

+7  A:

Use the SIunits package when working with any kind of units instead of trying to compose the unit abbreviations by hand.

\usepackage[mediumspace,mediumqspace,Grey,squaren,binary]{SIunits}
...
\unit{10.5}\mega\bit\per\second
\unit{0.2}\micro\second
\unit{9.81}\meter\per\second\squared
A:

You may want to consider running chktex over your document, it can find small nitpicks that can improve the typesetting and are normally quite hard to notice yourself. Things like using the right spacing, the right dash and many other things.

+2  A:

• Forget that DVI ever existed. pdftex is the most current and maintained implementation, and it's always frustrating to get a recent article with the bitmapped fonts from the metafont era, which don't display well on screen, and are often generated at too low a definition for modern laser printers.

• Type everything in UTF-8. That means \usepackage[utf8]{inputenc}, or give a try to XeTeX :)

• Stay light on the custom macros. I try to group semantic macros & environments separately from those that are pure convenience. In the past I tended to define macros for e.g. product or persan names, classes, methods, code examples, and what not, but in the end I find it's better to just type what you mean use one single \code{} macro (a semantic alias of \texttt{}), and if necessary do a global search and replace to ensure consistency throughout the document.

• Use collaboration notes. We have a set of adhoc macros for inserting TODOs and various comments while writing the article, but there are a few packages that do that and are already available in TeXlive (todonotes.sty is one).

+6  A:

Most of my tips have already been mentioned. The one tip I'd add is creating "namespaces" for different types of labels. For example, I use \label{eq:labelgoeshere} for equations, \label{tbl:labelgoeshere} for tables, \label{fig:labelgoeshere} for figures, etc.

For source code, I use the listings package.

+3  A:

One suggestion: use \colon instead of : in appropriate math. E.g. compare $f:X \to Y$ with $f \colon X \to Y$.

Except if you want to use : as a binary relation. For instance: If $f\colon G \to G$ is an involution, and $K=\ker f$, then $[G:K] = 2$.
Try \let\from=\colon to make your code more readable. Then you can say "If $f\from G \to G$..."
A:

Put all graphics preferably only in SVG into a separate graphics directory (in the following fig/). Generate the according PDFs on-the-fly in your makefile using svg2pdf.sh:

#!/bin/bash

for f in $*; do pdfname=${f%%.svg}.pdf;
inkscape $f --export-pdf=$pdfname;
pdfcrop $pdfname; echo${pdfname%%.pdf}-crop.pdf $pdfname; mv${pdfname%%.pdf}-crop.pdf $pdfname; done The makefile then just needs a special target for that: PDFs=$(SVGs:%.svg=%.pdf)
%.pdf: %.svg
fig/svg2pdf.sh $*.svg pdfs:$(PDFs)

Afterwards you can just throw the SVGs into the graphics directory and run make.

A:

For inserting source code with syntax highlighing, I find the listings package to be very good. It has some very nice options for controlling the column alignment too. For typesetting a language like Python I use:

\usepackage{listings}
\lstset{
language=Python,
basicstyle=\sffamily,
columns=fullflexible,
showstringspaces=false,
morekeywords={assert}
}

where the basicstyle and columns keys are the important ones. They tells listings to typeset the code in sans-serif fonts and to use the letters natural width. Otherwise an word like "mill" would look weird since "m" take up much more space than "i" and "l", when typeset in a sans-serif font.

+1  A:

I use the listings package, not least because it allows for source files/examples to be kept separate from the document text, and imported directly.

\usepackage{listings}
\lstset{language=Python}
\lstinputlisting{source.py}
+4  A:

Here's one I don't think has been mentioned yet.

When you are including figures via a \includegraphics and the like, don't specify the full pathname (use graphicspath to organize them) and don't specify the file suffix. Keep all of your figures in one canonical form (or one raster, one vector) and use make or the like to generate temporary files as needed.

This is much easier to organize, and also works well with different build paths (e.g. pdflatex vs latex->dvi->ps)

For example, if I have a file figures/figure1.png and I want to include it, my preamble will include something like

\usepackage{graphicx}
\graphicspath{{./figures/}}

And the document will have something like

\begin{figure}[htbp]
\centering
\includegraphics[width=0.8\textwidth]{figure1}
\caption{something terribly interesting}
\end{figure}

This works directly with pdflatex. If I need a .dvi, I'll have a makefile target that generates .eps files from .png files as needed, and either place them in './figures', or more likely in './eps' with an update to graphicspath above.

The benefits: Files can be organized into subdirs as needed, but you don't need to edit all over the place if you move them. You can also have different output targets without changing your source images and figures, and you won't have any surprised from conversion (like jpeg compression artifacts showing up in the pdf file you've generated from a .dvi)

A:

I'd recommend you stop using BibTeX and look at BibLaTeX instead. It's more powerful...

Not answering the question - best practice =/= most power. Idiomatic plain tex is more expressive than latex2e, but it is the latter that became the tex-based standard for document preparation and exchange.
+3  A:
1. Don't fuss about formatting on papers that you plan to submit for publication elsewhere - it makes later editing harder, and it's quite likely to cause problems at the typesetting stage. Stay close to elementary latex, and use only the latex packages you need. Don't use nonstandard fonts.
2. latexdiff is another tool worth knowing: it can be very helpful when explaining changes in collaborative editing.
3. Again for collaborative editing: once your reflist is complete, paste the .bbl file that bibtex produces into the latex file, in place of the \bibliography macro. This reduces a point of possible difficulty in the latex compile for your colleague.
4. Use the \message command the same way you would use printfs when debugging.
+26  A:
+2  A:

Avoid eqnarray. Use the align, align*, or split environments from amsmath instead.

+3  A:

Know the differences between hyphens, en- and em-dashes, and minus signs (-, --, ---, and $-$, respectively). Hyphens are for compound adjectives and breaking words across lines. En-dashes are for ranges, as in 7--10. Em-dashes are for setting off text---like this. Minus signs are for subtraction.

+1  A:

wdiff or git diff --color-words is incredibly helpful when comparing edits made by your colleague against the original document. (It only works if they don't comment out the stuff they're deleting.)