Best practices in LaTeX
[+158] [40] Federico A. Ramponi
[2008-10-10 23:04:59]
[ latex typesetting ]
[ http://stackoverflow.com/questions/193298/best-practices-in-latex ] [DELETED]

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?

I'll add this as a comment first and edit later if no-one complains. I would add on to "Comment out suppressed..." and continue with "or use version control." Version control and LaTeX are an amazing coupling. - Steven Noble
(22) Title is just too delicious. I want to answer "wear it clubbing, not to the office" and "watch out for slippery upholstery". - Jay Bazuzi
(4) rollback: "latex" and "LaTeX" are spelled the same, differing only in capitalisation. The camel case capitalisation LaTeX is an approximation to a realisation of a logo for latex. Hence "latex" is spelled correctly, and, though many latexphiles prefer "LaTeX", "latex" is not incorrectly capitalised. - Charles Stewart
(3) it is not, but every time I see it, I quiver at the idea of searching "latex" on the internet, in particular while at work. So I got used to proper capitalization ;) - Stefano Borini
(5) Stefano: Google search is case insensitive. - George Steel
(2) @Stefano: you can somewhat restrict "latex" google searches to LaTeX-related pages by adding "tex" to your search query. - Matthew Leingang
@George: I mean in the search results, not in my search query. - Stefano Borini
(2) See a similar question on TeX-SX: tex.stackexchange.com/questions/19264/… - N.N.
(2) This is a great question, but I guess this one should be moved to tex.sx - Ingo
[+92] [2009-12-31 08:06:44] Alok Singhal

Here's my list:

• Read the TeX FAQ [1]. It has a lot of good information, and is constantly updated.
• Use  nag  [2] Latex package. It warns the user about the usage of old packages or commands (for example, using \it, \tt, etc.). nag warns about the things mentioned in  l2tabu  [3] (Obsolete packages and commands).
• Use  fixltx2e  [4] package. It fixes some 'mistakes' in Latex. From the description:
• ensure one-column floats don't get ahead of two-column floats;
• correct page headers in twocolumn documents;
• stop spaces disappearing in moving arguments;
• allowing \fnysmbol to use text symbols;
• allow the first word after a float to hyphenate;
• \emph can produce caps/small caps text;
• bugs in \setlength and flushbottom.
• If you are typesetting any math, reading Math mode [5] by Herbert Voß is a must.
• If you really have to produce double-spaced documents, use setspace package instead of changing  baselinestreach  yourself [6].
• Typeset your document in draft mode to see how bad over- and underfull lines are, and if they are pretty bad, consider changing the wording a bit (but don't fuss too much over this, as the best wording is more important than minor typographical improvements). You can also help Latex by letting it hyphenate some words in this case.
• Use  booktabs  [7] to get much better-looking tables than Latex default.
• Use \centering instead of \begin{center} \end{center} to center things inside tables/figures etc.  \centering  doesn't add any additional vertical space. [8]
• Use  microtype  [9] for small-scale typographic enhancements ( character protrusion [10], font expansion, letter-spacing [11]).
• If you're creating PDF documents, use  hyperref  [12] to get hyperlinks in your document.
• Use  geometry  [14] package to set up page geometry instead of doing it manually.
• Use  fancyvrb  [15] to get precise control in verbatim listings.
• This is my personal view, and others may not agree, but I find the dotted lines in table of contents distracting and not really useful. I would rather have the page numbers right after the title in the "table of ..." entries. If you want to do that, see  titletoc  [16] package. The package documentation comes with several examples, and it is easy to change one of the examples to do exactly what you want it to do.
• If your document has a lot of technical figures, it might be a good idea to learn PGF/Tikz [17], sketch 3D [18], and pstricks [19], or a combination of those.
• To typeset units, use  siunitx  [20]. The package tries to replace sistyle, siunits, units, etc., is actively maintained, and the package writer is very active on comp.text.tex.
• Similar to above: use  numprint  [21] package to format numbers nicely (locale-specific, with commas as thousands separator, etc.).

I am sure I have missed some, but hopefully I will be able to add them later.

As an example of what is possible with Latex, I recommend looking at The Font Installation Guide [22] (for its typography).

Finally, one of the most important 'best practice', which I didn't mention above because it needs more space (no pun intended!) to explain than the list format would have allowed: understand the power of ~, the non-breakable space. Use it so that your document is easy to read. If you write:

This \textsc{dvd} is meant to be played with region 2 players only.


Latex may decide to break the line this way:

This DVD is meant to be played with region
2 players only.


To avoid the bad line-break, use ~:

This \textsc{dvd} is meant to be played with region~2 players only.


Now, region and 2 will not have a break between them.

[1] http://www.tex.ac.uk/cgi-bin/texfaq2html?introduction=yes
[2] http://www.tug.org/texlive/Contents/live/texmf-dist/doc/latex/nag/
[3] http://www.ctan.org/tex-archive/info/l2tabu/
[4] http://www.ctan.org/pkg/fixltx2e
[5] http://www.ctan.org/tex-archive/info/math/voss/mathmode/
[6] http://www.tex.ac.uk/cgi-bin/texfaq2html?label=linespace
[7] http://www.ctan.org/tex-archive/macros/latex/contrib/booktabs/
[8] http://texblog.net/latex-archive/layout/center-centering/
[9] http://www.ctan.org/tex-archive/macros/latex/contrib/microtype/
[10] http://wiki.contextgarden.net/Protrusion
[11] http://en.wikipedia.org/wiki/Letter-spacing
[12] http://www.tug.org/applications/hyperref/manual.html
[13] http://en.wikipedia.org/wiki/Binomial_nomenclature#Rules
[14] http://www.ctan.org/tex-archive/macros/latex/contrib/geometry/
[15] http://www.ctan.org/tex-archive/macros/latex/contrib/fancyvrb/
[16] http://www.ctan.org/tex-archive/macros/latex/contrib/titlesec/
[17] http://sourceforge.net/projects/pgf/
[18] http://www.frontiernet.net/~eugene.ressler/
[19] http://tug.org/PSTricks/main.cgi/
[20] http://www.ctan.org/tex-archive/help/Catalogue/entries/siunitx.html
[21] http://www.ctan.org/tex-archive/help/Catalogue/entries/numprint.html
[22] http://mirror.ctan.org/info/Type1fonts/fontinstallationguide/fontinstallationguide.pdf

+1, you had me at siunitx. I've been typesetting them via a custom macro that didn't work very well. - rcollyer
1
[+78] [2008-10-10 23:16:34] Mr Fooz

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 - Uri
(3) 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 Potts
(9) @Anthony: that's not about source control. That's about having backups (and a recovery plan) - Stefano Borini
2
[+59] [2008-10-13 04:36:52] Uri

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. - Mark Reid
(2) 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. - Mnementh
(8) Good tip. Actually, keeping one sentence per line helps when using VCS. For that reason now I prefer not to wrap the lines. - sastanin
(3) I don't suppose you have a emacs mode or macro to set this up? - dmckee
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 - Uri
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 :) - Damien Pollet
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. - Uri
(7) 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. - Stephen C. Steel
@Mnementh, what editor do you use that makes (soft wrap) linebreaks and keeps the indentation? Neither Vim nor TeXShop can do it... this question and this, too. - Kit
@Kit: jEdit: jedit.org - Mnementh
Breaking up paragraphs into multiple lines (whether its sentences or hard wrapping) is also useful when it comes to interpreting errors from the (La)TeX compiler. Line numbers in errors are more meaningful when they refer to one (or part of a) sentence, rather than an entire paragraph. - drfrogsplat
@Kit: TeXstudio displays soft-wrapped lines with same indent. Emacs can be configured to do it. - Beni Cherniavsky-Paskin
3
[+32] [2008-10-10 23:43:53] ejgottl

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

(5) latexmk is handy in this regard for the latex/bibtex side of things (see my answer below). - dreeves
A nice ready makefile is the "The Ultimate Latex Makefile", see below =) - Touko
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. - Rupert Nash
Scons can do that, to me it seems even more simple than a Makefile. - tmoisan
(2) After trying several kinds of super-complex makefiles, I discovered rubber and never looked back. - Roberto Bonvallet
4
[+32] [2008-10-10 23:52:35] Jon Shea

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}


Documentation for the packages used in these examples:

[1] ftp://ftp.tex.ac.uk/tex-archive/macros/latex/contrib/geometry/geometry.pdf
[2] http://merkel.zoneo.net/Latex/natbib.php
[3] http://www.ctan.org/tex-archive/macros/latex/contrib/booktabs/
[4] http://stackoverflow.com/questions/547508/in-latex-is-there-a-way-to-put-a-float-automatically-after-where-it-is-first-ref/547614#547614
[5] http://www.utexas.edu/ogs/etd/LaTeX/Mathematics+AMS/amsmdoc.pdf
[6] http://www.tug.org/texlive/Contents/live/texmf-dist/doc/fonts/amsfonts/amssymb.pdf
[7] http://mirror.math.ku.edu/tex-archive/macros/latex/contrib/cancel/cancel.pdf
[8] http://ctan.math.utah.edu/ctan/tex-archive/macros/latex/contrib/units/units.pdf
[9] http://www.tex.ac.uk/CTAN/macros/latex/contrib/fancyvrb/fancyvrb.pdf

(2) 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. - Svante
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. - Jon Shea
(1) Can you provide links to the documentation of those packages? You've given their names, but not what exactly they contain that is useful. - sykora
5
[+24] [2008-12-29 21:10:13] dreeves

I highly recommend the short math guide [1] which includes explicit best practices for typesetting math using AMSLatex [2] (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.

[1] ftp://ftp.ams.org/pub/tex/doc/amsmath/short-math-guide.pdf
[2] http://www.ams.org/tex/amslatex.html

6
[+22] [2008-10-20 13:54:02] John D. Cook

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.

(11) 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.) - Hudson
(1) (Of course, I still use $$since that is what I learned so many years ago...) - Hudson (3) I agree with formatting code, but I disagree with C++ style. ;) - Svante (1) I see that formatting like C code also multiplies the denominator of the fraction with c... :-) - Daan 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. :-) - John D. Cook
I agree with @Svante. To write every equation in a lengthy document like this would make it very difficult (at least for me) to parse the source code. - Daniel Miller
I also think this is too much space for an equation, but I very much agree with the overall spirit. I've seen mathematicians write 2-line long formulas with no whitespace at all, write nested enumerate environments with no indentation, and never insert empty lines for legibility (not even before \section)... There can be no agreement on the exact formatting, but surely some whitespace can help. - Beni Cherniavsky-Paskin
7
[+20] [2008-10-12 16:14:02] jk.

I use the KOMA-script package [1] 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 [2])

[1] http://www.ctan.org/tex-archive/macros/latex/contrib/koma-script/
[2] http://tug.ctan.org/cgi-bin/ctanPackageInformation.py?id=koma-script

8
[+20] [2008-10-13 08:35:18] Mark Reid

This may not be the type of tip you are after but if you haven't already,take a look at LyX [1]. 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] http://www.lyx.org/

+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 - Kena
If you want realtime LaTeX I would suggest Bakoma Tex instead - it is far more powerful and convenient. - nikow
I will not downvote since lyx worked for you, but I like standalone latex more. - phaedrus
9
[+18] [2008-12-29 21:19:32] Uri

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 - dmckee
I often need them since I deal with long documentations, and my advisor deals with them piecemeal. - Uri
(6) You might try the todonotes package, which provides this sort of thing. Esp with the inline option. - Paul Biggar
Hehe, I like the lighter grays for less stable text parts. - Frank
10
[+17] [2008-12-30 21:00:04] dreeves

I recommend latexmk [1] which, with -pvc switch (for "preview continuously"), will recompile 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: Don't make me manually abort a LaTeX compile when there's an error [2]

[1] http://www.phys.psu.edu/~collins/software/latexmk-jcc/
[2] http://stackoverflow.com/questions/738755/dont-make-me-man

Do I need latexmk for that when I have Skim? - Masi
(1) 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. - dreeves
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. - Frank
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. - dreeves
11
[+16] [2008-10-20 14:11:47] John D. Cook

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 [1]. 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 [2].

[1] http://www.statistik.lmu.de/~leisch/Sweave/
[2] http://www.johndcook.com/troubleshooting_sweave.html

here comes knitr in handy and can fully replace the Sweave because it is a developed extension of Sweave and dealt with many of its problems. If you use R for analysis I highly recommend Rstudio as a working environment (fully support knitr, git, and svn version control as well). Graphical display of the all of the commits you do with the version control. But, you might want first to read about git or svn before digging there uninformed. - doctorate
12
[+15] [2009-04-23 04:08:58] las3rjock

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.

(1) I prefer labels like eq_Equation1 to eq:Equation1 because by default my editor (vi) can auto-complete the first type but not the second. - FJDU
13
[+14] [2009-06-03 18:50:44] simon

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)

14
[+13] [2009-03-09 15:05:34] x-way

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


(3) siunitx should be preferred over SIunits. See also this question: tex.stackexchange.com/questions/2248/… - Denilson Sá
15
[+11] [2008-10-11 01:22:26] Steven Noble

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

(1) 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... - Federico A. Ramponi
16
[+10] [2008-10-10 23:34:59] Draemon

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.

(1) Eclipse has a plugin for latex syntax highlighting as well - Kena
(2) kile and texnicenter are good editors IMHO - Krystian
17
[+10] [2008-10-12 16:02:26] Eric

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

(1) By the way, someone answered "lots of margarine on your legs". My fault. - Federico A. Ramponi
coffee in my nose from laughing ... ow ... - Eric
(12) @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. :-) - Alok Singhal
18
[+10] [2008-11-05 09:49:44] Gianluca Della Vedova
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. - sastanin
19
[+8] [2009-12-03 10:48:19] Charles Stewart
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 [1] 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.
[1] http://www.ctan.org/tex-archive/support/latexdiff/

20
[+7] [2009-04-16 22:23:49] Damien Pollet

• 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).

21
[+7] [2010-04-21 12:07:17] uckelman

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.

22
[+6] [2009-05-10 20:00:28] David Brown

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$. - Matthew Leingang
(4) Try \let\from=\colon to make your code more readable. Then you can say "If $f\from G \to G$..." - Matthew Leingang
23
[+5] [2011-04-13 20:46:05] Elton Carvalho

On \includegraphics, I might add that I see lots of people using [scale=xx] and, by trial and error, setting up the image size.

• Create the figure in the final size: Create the PDF or EPS with the correct size, or the PNG or other bitmap image with the correct dimensions, considering the DPI (300-600 for print, 72 for electronic display)
• use [width=0.x\textwidth], which guarantees a consistent image size relative to text.

(1) I like the point about width=.... See also tex.stackexchange.com/questions/275/… - phaedrus
24
[+4] [2008-10-10 23:50:01] ejgottl

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

25
[+4] [2008-10-13 08:05:13] Treb

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. - Federico A. Ramponi
Perhaps I should change the word "concept"? "thing"? "object"? Please suggest... - Federico A. Ramponi
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 - Treb
26
[+4] [2008-12-29 21:16:15] dreeves

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.

27
[+4] [2009-05-22 13:18:27] Edd

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}


28
[+4] [2010-02-04 09:50:39] Frank

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

Why should I avoid eqnarray environment usage? - Israel
29
[+3] [2009-03-09 14:53:44] Touko

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

[1] http://www.acoustics.hut.fi/u/mairas/UltimateLatexMakefile/

30
[+3] [2009-04-01 12:29:54] Baruch Even

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.

31
[+3] [2010-07-09 15:11:54] Ken Bloom

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

32
[+3] [2011-08-26 10:26:16] Ruggero Turra
• ### Try to separate style from content

Unfortunately LaTeX doesn't force you to do it (as in docbook) but it's a good pratice.

For example if you need to write a vector don't write $\vec{v}$, but write $\vecb{v}$, so you can change all vectors from \providecommand{\vecb}[1]{\boldsymbol{#1}} to \providecommand{\vecb}[1]{\vec{#1}} only editing one line

• ### Use amsmath

\begin{figure}
\centering
\includegraphics[width=\myimagewidth]{img/myimage}
\caption{my image}
\label{img:image1}
\end{figure}


33
[+2] [2009-05-10 20:31:05] wr.

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.

34
[+2] [2009-05-22 13:04:23] Martin Geisler

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.

35
[+1] [2008-10-10 23:13:31] ConcernedOfTunbridgeWells
• Lgrind [1] is a good tool for rendering source code listings in LaTeX.
[1] http://www.ctan.org/tex-archive/help/Catalogue/entries/lgrind.html

36
[+1] [2008-10-20 14:14:31] Anthony Potts

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.

37
[+1] [2008-12-11 22:36:31] Niel

I disagree somewhat with the practise

"Use macros to represent concepts, not to type less"

because sometimes, the semantics of the macro you're using isn't very interesting to anyone who would probably read the source. I routinely define the following:

\def\x{\times}
\def\ox{\otimes}
\def\C{\mathbb C}
\def\Z{\mathbb Z}

and so on, to denote cartesian products, tensor products, the complex numbers, the integers, etc; all standard objects for my audience. The meaning of these are about as meaningful to the interested reader of my source-code as the corresponding output is to my intended audience, because I name them suggestively (if tersely). And while the macros produced by

\def\cH{\mathcal H}
\def\sS{\mathscr S}

may be less obvious, they aren't any less obvious than the corresponding roman-italics variables "H" or "S" would be in context.

Sometimes, all you want is to have more variables at your fingertips; semantically named variables such as \ComplexNbrs or \TensorProduct, while nice in a very pretty meta-document sense, mostly produce unnecessary typing for the author for effectively no gain.

Perhaps the key is in the choice of where you wish to save keystrokes --- to do it for appropriate and self-contained noun-objects, perhaps --- but I use macros to save typing to such an extent that I have written macros to define entire families of keystroke-saving macros.

\C and \Z, at least, are concepts: the set of complex numbers, and the set of integers, and they should have macros that express that concept in one command. - Ken Bloom
38
[+1] [2009-12-01 23:15:10] Seamus

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. - Charles Stewart
39
[0] [2011-08-24 20:36:26] michael

I like using minted [1] for typesetting source-code. Minted is very easy to use and allows for inline code as well as inclusion of complete source files. It is based upon pygments [2] and has support for a huge amount of languages plus it comes with several nicely styled color themes. Please excuse the formatting of this post, I'm sending this from my iPhone as I enjoyed the thread so much, I wanted to contribute.

40