LaTeX notes
Table of Contents
This is an excellent reference:
http://en.wikibooks.org/wiki/LaTeX
Tools
Some editors for LaTeX (there are many others):
- TeXStudio
- VSCode with LaTeX Workshop
- AucTeX in Emacs
Many of them have spell checkers but not grammar checkers. TexStudio [1] [2], VSCode [1], and Emacs [1] can integrate Language Tool, the grammar checker for LibreOffice.
Layout
Option for setting margins:
\usepackage{fullpage}
OR
\usepackage[hmargin=25mm,vmargin=25mm]{geometry}
Example of adding header/footer:
\usepackage{fancyhdr} \renewcommand{\footrulewidth}{0.4pt} \topmargin -25pt \headsep 15pt \pagestyle{fancy} \fancyhead[L]{\emph{Running title}} \fancyhead[R]{Author name} \fancyfoot{} \fancyfoot[C]{\thepage}
For \onehalfspacing
command, use setspace
package.
To turn off automatic indentation, use parskip
package. To indent all paragraphs, use indentfirst
package.
Fonts
Sans serif
Sans-serif text and math:
\renewcommand\familydefault{\sfdefault} \usepackage[cm]{sfmath} % \usepackage{helvet} % optional
Math
Bold Greek letters: use bm
package, which invokes \boldmath
or \boldsymbol
as necessary. Example usage: \bm{\beta}
.
Many engineering equations use multi-character variable names. E.g., instead of x
, y
, etc., people might name their variables to reflect the physical phenomenon being modeled. E.g., RH
(relative humidity), MW
(molecular weight), OA
(organic aerosol). In this case, use $\mathit{RH}$
instead of just $RH$
.
Functions typically have their corresponding LaTeX commands: e.g., \exp
, \ln
, \sin
.
Multiplication operators such as \times
and \cdot
is preferred to *
.
Parentheses, brackets can be automatically scaled with contents (e.g., fractions and subscripts): \left( \ldots \right)
, \left[ \ldots \right]
, \left\{ \ldots \right\}
, \left\langle \ldots \right\rangle
.
Use amssymb
and upgreek
packages for some symbols.
Subscripts/superscripts
For consistent subscript size:
\usepackage{subdepth}
Conventionally, math expressions were used for subscripts/superscripts even in text. E.g., PM$_{2.5}$
. Now there is \textsubscript{}
and \textsuperscript{}
, as well as other options.
Chemistry
Use the mhchem
package with explicit specification of version number:
\usepackage[version=4]{mhchem}
Example usage: \ce{NO2}
, \ce{O3}
, \ce{NO_x}
.
Copernicus has a \chem{}
macro but operates differently. Example usage: \chem{NO_2}
, \chem{O_3}
, \chem{NO_x}
.
Captions
\usepackage[font=md,labelfont=bf]{caption} \captionsetup[figure]{font=small,labelfont=small}
Defining macros
Usage of \newcommand{}
and \renewcommand{}
.
Optional space after the command
When defining a macro with no arguments, an empty space should be created using {}
. For instance, \newcommand{\pmfine}{PM\textsubscript{2.5}}
should be invoked as \pmfine{}
. Alternatively, the xspace package can be used with the command \xspace
. Example: \newcommand{\pmfine}{PM\textsubscript{2.5}\xspace}
. See section on units for another example.
Number in variable names
You cannot use numbers in macros. Rather than \newcommand{\x1}{variable1}
, use \newcommand{\x}[1]{variable#1}
. In your latex file, you would then invoke using \x{1}
.
Units
Use siunitx
package. \si
for units (e.g., \si{\meter.\second^{-2}}
) and \SI
for both numbers and units (e.g., \SI{9.8}{\meter.\second^{-2}}
). More examples below. Common prefixed units have their own abbreviated command - e.g., \cm
can be used in place of \centi\meter
- enable these abbreviations with load=abbr
:
\usepackage[load=abbr]{siunitx} \usepackage{xspace}
Define macros:
\newcommand{\invcm}{\si{\cm^{-1}}\xspace} \newcommand{\massc}{\si{\micro\gram.\meter^{-3}}\xspace}
Mathematical expressions
Enclose expressions in \ensuremath{}
so that they can be used inline in also within mathematical expressions without using $
. Also use xspace. Example — if you have a variable typically written $\mathit{MW}$
, you can recode it as \MW
:
\newcommand{\ensuremath{\mathit{MW}}\xspace}
This can be used as \MW = 18.01 \si{\gram.\mole} in text, or $\MW = 18.01 \si{\gram.\mole}$
.
Line numbers
\usepackage[displaymath,mathlines]{lineno}
AMS math environments conflict with line numbers:
\newcommand*\patchAmsMathEnvironmentForLineno[1]{% \expandafter\let\csname old#1\expandafter\endcsname\csname #1\endcsname \expandafter\let\csname oldend#1\expandafter\endcsname\csname end#1\endcsname \renewenvironment{#1}% {\linenomath\csname old#1\endcsname}% {\csname oldend#1\endcsname\endlinenomath}}% \newcommand*\patchBothAmsMathEnvironmentsForLineno[1]{% \patchAmsMathEnvironmentForLineno{#1}% \patchAmsMathEnvironmentForLineno{#1*}}% \BeginDocument{% \patchBothAmsMathEnvironmentsForLineno{equation}% \patchBothAmsMathEnvironmentsForLineno{align}% \patchBothAmsMathEnvironmentsForLineno{flalign}% \patchBothAmsMathEnvironmentsForLineno{alignat}% \patchBothAmsMathEnvironmentsForLineno{gather}% \patchBothAmsMathEnvironmentsForLineno{multline}% }
The code above is included in the preamble file here. Example usage:
\input{preamble_mathlineno}
Local environments
For simple tasks:
\{ \appendix % or \renewcommand{} etc. {...stuff...} \}
OR, for more complex tasks:
\begingroup
\appendix
{...stuff...}
\endgroup
Placing custom .sty and .bst files
Check where TEXMFHOME is
kpsewhich -var-value=TEXMFHOME
Then check out this table to place the file in the appropriate location. See also this reference.
On MacOS, they are typically:
~/Library/texmf/bibtex/bst/copernicus.bst ~/Library/texmf/bibtex/bst/elsarticle-harv.bst ~/Library/texmf/tex/latex/base/copernicus.cls ~/Library/texmf/tex/latex/base/copernicus2.cls ~/Library/texmf/tex/latex/local/natbibspacing.sty ~/Library/texmf/tex/latex/local/undertilde.sty
Handling file names
Using the tilde:
\bibliographystyle{copernicus} \bibliography{\string~/git/projects/bibfile/references}
\usepackage{graphicx} \usepackage[space]{grffile} [ ... ] \includegraphics{A file with spaces}
Period/dot in graphics file name:
\includegraphics{{A.file.with.periods}.pdf} \includegraphics{{{A.file.with.periods}}}
\input{"File\space Of\space Mine"}
Bibliographies
For journal articles, use bibtex template provided by publisher (not biblatex). Biblatex is helpful in the drafting stage, in that missing references are indicated by their .bib key rather than "??" in citations as with bibtex. It is simple to change out biblatex with bibtex for publication.
Biblatex
The code below is included in the preamble file here. Example usage:
\input{preamble_biblatex} \addbibresource{references}
Preamble
Loading the package:
\usepackage[ natbib % for citation citestyle=authoryear, % for citation maxcitenames=2, % for citation uniquelist=false, % for citation uniquename=false, % for citation sorting=nyt, % for bibliography date=year, % for bibliography bibstyle=ieee, % for bibliography maxbibnames=99, % for bibliography backend=biber, block=none ]{biblatex}
\DeclareNameAlias{sortname}{last-first} \DeclareNameAlias{default}{last-first}
Use hanging indentation:
\defbibenvironment{bibliography} {\list {} {\setlength{\leftmargin}{\bibhang+1em}% \setlength{\itemindent}{-\leftmargin}% \setlength{\itemsep}{\bibitemsep}% \setlength{\parsep}{\bibparsep}}} {\endlist} {\item}
Create doi links in bibliography:
\ExecuteBibliographyOptions{url=false,eprint=false} \newbibmacro{string+doi}[1]{% \iffieldundef{doi}{#1}{\href{http://dx.doi.org/\thefield{doi}}{#1}}} \DeclareFieldFormat{doi}{\usebibmacro{string+doi}{doi:#1}}
Also in the preamble, specify location of .bib file:
\addbibresource{references}
Main document
Change bibliography title:
\printbibliography[title=Bibliography]
No bibliography title:
\renewcommand\refname{} \vspace{-5ex} \printbibliography
Multiple bibliographies:
\section*{Section 1} \begin{refsection} \nocite{*} \vspace{-5ex} \printbibliography[title=\sectiontitle] \end{refsection}
Natbib and bibtex
natbib
and bibtex
(instead of biblatex
) still required for journal submissions.
Don't print reference section title
\renewcommand{\bibname}{} \renewcommand{\refname}{}
Don't print reference section title at all (with natbib)
\renewcommand{\bibsection}{}
Don't show reference section title on TOC
\renewcommand{\bibsection}{\section*{\bibname}}
Reference section title as section head
\renewcommand\refname{\vspace{-5ex}} \section{References} \bibliographystyle{...} \bibliography{...}
Extracting subset of bibliographies
E.g., for distribution with tex file. Use bibtool.
To build, download and unpack bibtool.zip:
./configure make --file=makefile.unx sudo make --file=makefile.unx install sudo make --file=makefile.unx install.man make --file=makefile.unx clean
To build docs:
cd doc
make
To use:
bibtool --preserve.key.case=on -x file.aux -o refs.bib
Unicode characters in .bib file
First, try importing:
\usepackage[T1]{fontenc} \usepackage[utf8]{inputenc}
If this is insufficient, try substituting each problematic unicode character:
\DeclareUnicodeCharacter{2202}{ }
To find which specific characters are causing problems, a great macro that can be placed in the preamble is introduced here:
\usepackage{stringenc} \usepackage{pdfescape} \makeatletter \renewcommand*{\UTFviii@defined}[1]{% \ifx#1\relax \begingroup % Remove prefix "\u8:" \def\x##1:{}% % Extract Unicode char from command name % (utf8.def does not support surrogates) \edef\x{\expandafter\x\string#1}% \StringEncodingConvert\x\x{utf8}{utf16be}% convert to UTF-16BE % Hexadecimal representation \EdefEscapeHex\x\x % Enhanced error message \PackageError{inputenc}{Unicode\space char\space \string#1\space (U+\x)\MessageBreak not\space set\space up\space for\space use\space with\space LaTeX}\@eha \endgroup \else\expandafter #1% \fi } \makeatother
Download this preamble file here. Example usage:
\input{preamble_utf8macro}
Then monitor the .log file to check the offending character(s).
Cross referencing with xr
If you have two files, master.tex and supportinginfo.tex, you would include these in your respective preambles:
master.tex
\usepackage{xr} \externaldocument{supportinginfo} \usepackage{hyperref}
supportinginfo.tex
\usepackage{xr} \externaldocument{master} \usepackage{hyperref}
Deleting .aux and extra files (for both .tex files) prior to compiling may be necessary when there are errors.
Spell/grammar check
Apart from spell checking or grammar checking (using Language Tool), another option is to export an ASCII file using detex
and opening the file in MS Word. In a shell command line:
detex master.tex intro.tex methods.tex results.tex conclusions.tex > alltext.txt
Alternatively, you can export to a Rich Text Format (.rtf) file to open in MS Word using pandoc:
pandoc master.tex -o output.rtf --bibliography references_1.bib -s
These methods can also provide an (very) approximate character or word count. (?)
Compilation
Put \batchmode
at the top of your .tex file (or \nonstopmode
for more verbose output) to avoid stopping when there is an error.
To avoid having to repeat pdflatex
, bibtex
, pdflatex
, and pdflatex
, use latexmk
:
latexmk -pdf texfile
On Max OS X, latexmk
can be installed with texlive
.