Hippocamplus My Second Memory

LaTeX

A lot of good information in the LaTeX Wikibook.

Standard packages

This is my default (more or less) :

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{tabularx}
\usepackage[colorlinks=true,linkcolor=black,citecolor=black]{hyperref}
\usepackage{amsmath, amssymb, amsthm}
\usepackage{float}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{fullpage}

TinyTeX

TinyTeX is a lightweight LaTeX distribution where we download only what we need. It’s a R package. Once installed, run install_tinytex() to install a first version of TinyTeX. Then install additional packages with tlmgr_install("pkg"). To find which package provides a particular xxx.sty run tlmgr_search("/xxx.sty").

Misc

Document class

\documentclass[12pt, a4paper]{article}
  • Classic classes: article, report, book.
  • Default font size is 10pt.
  • Other cool options: twocolumn, landscape.

Page size

Page types in \documentclass[letterpaper]{article} include letterpaper, a4paper (and more).

Custom page/margins:

\usepackage[paperwidth=8.5in, paperheight=11in, top=0.5in, bottom=0.5in, left=1in, right=0.5in]{geometry}

Or margin= to apply the same margin on each side.

Font sizes

\tiny, \scriptsize, \footnotesize, \small, \normalsize, \large, \Large, \LARGE, \huge, \Huge.

Change the symbol in lists

\renewcommand{\labelitemi}{\textgreater}

Here are some appropriate symbols: \ast, \star, \diamond, \blacktriangleleft, \blacktriangleright, \rightarrow, \Rightarrow.

Math calligraphy

The two most popular math calligraphy are used with :

  • $\mathcal{A}$ for calligraphy.
  • $\mathbb{A}$ for blackboard (e.g. sets).
  • $\mathbf{A}$ for bold.

Languages and encoding

At some time when writing in French or Spannish I used:

\usepackage[utf8]{inputenc}
\usepackage[frenchb]{babel}
\usepackage[T1]{fontenc}

and

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[spanish]{babel}

An accent was specified as \'i.

Table of contents

Changing the title of the section created by \tableofcontents:

\renewcommand{\contentsname}{Table of Contents}

To manually add an un-numbered section to the TOC (here at the chapter level):

\addcontentsline{toc}{chapter}{Disclaimer}

To set the depth of the TOC:

\usepackage{tocbibind}
\setcounter{tocdepth}{2}

To set the space between the number and the title in list of figures/tables (e.g. if custom long numbers):

\usepackage{tocloft}
\setlength{\cftfignumwidth}{3em}

Metadata

To specify the PDF’s metadata (title, author, etc):

\usepackage[pdfauthor={AUTHOR},pdftitle={TITLE},pdfsubject={SUBJECT},pdfkeywords={KEYWORDS},pdfproducer={LaTeX},pdfcreator={pdflatex}]{hyperref}

Figures

Position

  • [h] means here.
  • [t] means at the top of the page.
  • [p] means on its own page.

I usually use [ht] for small/medium figures, and [htp] for large ones.

Sub-figures

After adding \usepackage{subcaption}, use like this:

\begin{subfigure}[b]{.48\textwidth}
    \includegraphics{example.pdf}
    \caption{}
    \label{fig:example}
end{subfigure}

For more custom organization of the sub-figures, feel free to use minipage environment. To force a caption number/letter, use \addtocounter{subfigure}{XX}. For example, to have the second subfigure as a long vertical panel on the right and figure {} and {}, smaller on the left:

\begin{figure}[htp]
    \begin{minipage}[c]{.4\textwidth}
        \begin{subfigure}[b]{\linewidth}
            \includegraphics{example.pdf}
            \caption{}
            \label{figa}
        \end{subfigure}
        \addtocounter{subfigure}{1}
        \begin{subfigure}[b]{\linewidth}
            \includegraphics[page=3]{example.pdf}
            \caption{}
            \label{figc}
        \end{subfigure}
    \end{minipage}
    \begin{minipage}[c]{.6\textwidth}
        \addtocounter{subfigure}{-2}
        \begin{subfigure}[b]{\linewidth}
            \includegraphics[page=2]{example.png}
            \caption{}
            \label{figb}
        \end{subfigure}
    \end{minipage}
    \caption{Whole figure caption}
\end{figure}

Supplementary figures

The counter and style for supplementary figures (and tables) can be changed. I place this block at the beginning of the supplementary figure section:

\setcounter{figure}{0}
\renewcommand{\thefigure}{S\arabic{figure}}

Moreover, some journals require the supplementary figures to be named Supplementary Fig. 1. As it is, with the configuration above, it would look like Fig. S1 when using Fig. \ref{fig:toto}. The only solution I can think of is to manually write or not the Supplementary and remove the S in the number. But it’s painful. Eventually I could write a small script that does this automatically.

Side-note: I don’t like this style. Ok it looks a bit more fancy but using S12 is shorter and clearer, and avoids any confusion even when citing multiple figures.

To list tables: \listoffigures

Tables

Control tabular width

\resizebox{.8\textwidth}{!}{
    TABULAR
}

Add vertical padding

{{\arraystretch}{1.3}
    TABULAR
}

Supplementary tables

Similar to figures I use:

\setcounter{table}{0}
\renewcommand{\thetable}{S\arabic{table}}%

To list tables: \listoftables

Spanning columns/rows

  • \multicolumn{2}{c|}{Multi-column} for a column spanning 2 columns.
  • \multirow{2}{*}{Multi-row} for a row spanning 2 rows.
  • \cline{2-10} to avoid \hline crossing a multi-row cell (one the first column).

Align columns

In Emacs, place the cursor within the tabular and press M-x align-current.

Rectangular selection/cut/paste

In Emacs, the columns can be “easily” rearranged using rectangular selection. Depending on Emacs’ version it could be:

  • C-x space starts the selection.
  • C-x r k cut the selection.
  • C-x r y paste the selection, considering the cursor in the top-left corner of the desired location.

Tables from R

Package knitr has a function kable to easily format a data.frame in LaTeX format.

Code blocks

The easiest is to use Listings environment.

In Emacs to avoid misinterpreting special character (e.g. $ or _) I added to .emacs :

(setq LaTeX-verbatim-environments-local '("lstlisting"))

Then in the LaTeX document I setup the lstlisting environment with something like:

\lstset{
  basicstyle=\scriptsize\ttfamily, % the size of the fonts that are used for the code
  breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
  breaklines=true,                 % sets automatic line breaking
  frame=single,                    % adds a frame around the code
  keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code
  language=sh,                     % the language of the code
}

For manuscripts

Abstract

An abstract environment exists:

\begin{abstract}
Genetics has been shown to be important...
\end{abstract}

Author affiliation

Using \usepackage{authblk}, the authors’ affiliations can be defined like this:

\author[1,2]{Jean Monlong}
...
\affil[1]{Department of Human Genetics, McGill University, Montréal, H3A 1B1, Canada}
\affil[2]{McGill University and Génome Québec Innovation Center, Montréal, H3A 1A4, Canada}
...

Text formatting

  • \linespread{1.6} for double-spacing.
  • To add line numbers, lineno package:
\usepackage[modulo]{lineno}
\linenumbers

Notes/comments

\usepackage{todonotes}
\newcounter{mycomment}
\newcommand{\comment}[2][]{%
  \refstepcounter{mycomment}%
  {%
    %\setstretch{0.7}% spacing
    \todo[color={red!100!green!33},size=\tiny]{%
      \textbf{[\uppercase{#1}\themycomment]:}~#2}%
  }}
\newcommand{\commentil}[2][]{%
  \refstepcounter{mycomment}%
  {%
    %\setstretch{0.7}% spacing
    \todo[inline,color={red!100!green!33},size=\tiny]{%
      \textbf{[\uppercase{#1}\themycomment]:}~#2}%
  }}

To add a note: \commentil[NAME]{This is an inline comment}.

Main text and supplements in two documents

It’s easier to have the two documents separated with their own bibliography. Then no need to manually split the pdf (and likely lose links).

Using the xr package, we can specify other documents where to find references (figures, tables, sections).

In the main.tex document:

\usepackage{xr}
\externaldocument{suppmap}

And in the suppmat.tex document:

\usepackage{xr}
\externaldocument{main}

On Overleaf, they use a variant where the suppmat.tex is not compiled but its references can still be used in the main.tex using:

\usepackage{xcite}
\usepackage{xr}
\makeatletter
\newcommand*{\addFileDependency}[1]{% argument=file name and extension
  \typeout{(#1)}
  \@addtofilelist{#1}
  \IfFileExists{#1}{}{\typeout{No file #1.}}
}
\makeatother

\newcommand*{\myexternaldocument}[1]{%
    \externaldocument{#1}%
    \addFileDependency{#1.tex}%
    \addFileDependency{#1.aux}%
}
\myexternaldocument{SuppMat}

Compare versions and highlight revisions

The latediff Perl script works well. For example to compare two versions I use:

git show COMMIT:main.tex > main-old.tex
git show COMMIT:suppmat.tex > suppmat-old.tex

latexdiff main-old.tex main.tex > main-diff.tex
latexdiff suppmat-old.tex suppmat.tex > suppmat-diff.tex

Then compile main-diff.tex and suppmat-diff.tex normally.

One figure = one file

I’d like to do some observational humor for you now, I hope you can identify with it: hey ! Don’t you hate… when you have finished preparing a submission and you realize you have to save every supplementary figure in its own file ?

Joke/frustration aside, a quick way to do that keeping the sub-figures organization together and the PDF format, is to reformat the latex file to remove the figures’ \caption and the page numbers (\pagestyle{empty}) and run something like:

for ii in `seq 1 20`
do
    pdfjam SuppFigs.pdf $ii -o temp.pdf
    pdfcrop --margins 10 temp.pdf FigureS$ii.pdf
done

Bibliography

I use \usepackage[comma,super]{natbib} and the commands:

\bibliographystyle{unsrtnat}
\bibliography{library.bib}

Reduce long list of authors

To change a long list of authors into “First Author et al” in the references, use a custom .bst file.

I downloaded the original version of the file there and change the FUNCTION {format.names} part by

INTEGERS { max.num.names.before.forced.et.al num.names.shown.with.forced.et.al }

FUNCTION {format.names}
{ 's :=
  #1 'nameptr :=
  #5 'max.num.names.before.forced.et.al :=
  #1 'num.names.shown.with.forced.et.al :=
  s num.names$ 'numnames :=
  numnames 'namesleft :=
    { namesleft #0 > }
    { s nameptr "{f.~}{vv~}{ll}{, jj}" format.name$ 't :=
      nameptr #1 >
        { nameptr num.names.shown.with.forced.et.al #1 + =
          numnames max.num.names.before.forced.et.al >
          and
            { "others" 't :=
              #1 'namesleft :=
            }
            { skip$ }
          if$
          namesleft #1 >
            { ", " * t * }
            { t "others" =
                { " " * "et~al." emphasize * }
                { numnames #2 >
                    { "," * }
                    { skip$ }
                  if$
                  " and " * t *
                }
              if$
            }
          if$
        }
        't
      if$
      nameptr #1 + 'nameptr :=
      namesleft #1 - 'namesleft :=
    }
  while$
}

This allows maximum five authors before it switches to “First Author et al” mode. These numbers are defined in lines with 'max.num.names.before.forced.et.al := and 'num.names.shown.with.forced.et.al :.

I put this new .bst file in the folder of my .tex file and called it in the style command: \bibliographystyle{unsrtnat5}.

“Name Year” style

I used \citep{} with this configuration:

\usepackage{natbib}
\bibpunct{ (}{)}{;}{a}{}{;}

Order of initials

To get Simpson H. instead of Homer Simpson I changes the .bst file line in the format.names function to :

{ s nameptr "{vv~}{ll~}{f.}{, jj}" format.name$ 't :=

No URL or DOI

There are nicer option with biblatex but since I’m still using bibtex I went into the .bst file and changed the formatting functions:

FUNCTION {format.url}
{ "" }
%%{ url empty$
%%    { "" }
%%    { new.block "URL \url{" url * "}" * }
%%  if$
%%}

FUNCTION {format.doi}
{ "" }
%%{ doi empty$
%%    { "" }
%%    { new.block "\doi{" doi * "}" * }
%%  if$
%%}

Presentations

Changing the font

By default, Beamer uses a sans-serif font. It looks a bit harsh. I find the Palatino font easier on the eye. To switch to serif font and choose the Palatino, I add at the beginning of the document:

\renewcommand*{\familydefault}{\rmdefault}
\renewcommand*\rmdefault{ppl}

Section slides

To introduce sections, Beamer can automatically insert slides. These automated slides can be defined with:

\AtBeginSection{
  \begin{frame}
    \begin{center}
      \structure{\Large\bf \insertsection}
    \end{center}
  \end{frame}
}
\AtBeginSubsection{
  \begin{frame}
    \begin{center}
      \structure{\large \insertsubsection}
    \end{center}
  \end{frame}
}

Themes

I tend to use the minimalist default theme, remove the navigation bar but add slide number:

\usetheme{default}
\setbeamertemplate{navigation symbols}{}
\setbeamertemplate{footline}[page number]

For an important presentation, I could use a more fancy theme, such as the Metropolis theme or the Execushares one. Eventually I would like to mix and customize these two (see current state there).

Background image

For the acknowledgment slide or for more informal presentations, I sometimes want to use a specific image as background for a slide.

{
\usebackgroundtemplate{\includegraphics[width=\paperwidth]{pic.jpg}}%
\begin{frame}
\end{frame}
}

Backup slides

To add extra slides at the end of the presentation without increasing the total number of slides displayed:

\appendix
\newcounter{finalframe}
\setcounter{finalframe}{\value{framenumber}}

%% EXTRA SLIDES

\setcounter{framenumber}{\value{finalframe}}