# LaΤeΧ

### …and ΤeΧ, and ConTeXt and XeTeX and TeXleMeElmo

Usefulness: 🔧 🔧 🔧
Novelty: 💡
Uncertainty: 🤪
Incompleteness: 🚧 🚧 🚧

(Thanks fun.fnord.eu.)

The least worst mathematical typesetting system. One of the better scoured of the filthy pipes in the academic plumbing. De facto standard for mathematicians, especially those who are not so impertinent as to insist in writing in non-English languages, or are not so shallow as gainsay the simple delights of the painstaking handicraft of manually setting line breaks, or who have grad students who will deal with all that for free. That is, a tool which meets the needs of that endangered animal, the Tenured Academic, and that the rest of us survive.

Other alternatives include

1. using MS Word, and
2. stabbing your eyeballs with a pencil

… each of which I regard as similarly undesirable, and, to be clear, both even less desirable than LaTeX itself. Just because LaTeX is the best does not mean it is not also the least worst.

I am aware there are differences due to various different engines, formats, macro systems etc, giving us ConTeXT and LaTeX and TeX and pdfTeX and XeTeX and LuaTeX, and that they are all refreshingly different in their choices of pain-points, whether in in formatting, interoperation, character set handling, compatibility, preferred name capitalisation, or community support. I am cognisant of the buffet of failure cases I could choose from, if only in broad outline. However, standards lock-in being what it is, I believe I must avoid arranging the deckchairs of incremental improvement on this sinking ship. If I must do something, it will be to discretely wait over there, near the lifeboats, for some amped-up scholarly version of Markdown to come rescue me from the entire tiresome problem.

## History

Eddie Smith, From boiling lead and black art: An essay on the history of mathematical typography; the only thing on this page you might conceivably read for pleasure.

Robert Kosara has an excellent rant:

The tools of the trade for academics and others who write research papers are among the worst software has to offer. Whether it’s writing or citation management, there are countless issues and annoyances. How is it possible that this fairly straightforward category of software is so outdated and awful?

Grad students, Robert, and their zero-marginal-cost labour. The same labour undervaluation that keeps slave economies from developing the steam engine.

Here is a more pious take by Graham Douglas, What’s in a name: a guide to the many flavours of TeX.

## Reverse LaTeX

Get LaTeX back from screen captures or even photos (!) of (formatted) equations Mathpix. They also offer a mathematical notebook, snips. Or sketch that one tricky symbol into detexify.

Or! Leave the machines behind! Train yourself in speed LaTeX transcription via the gamified math typing game TeXnique.

## Unicode

### Vanilla TeX

I put this at the start of every file I touch.

% !TEX encoding = UTF-8 Unicode

then after the documentclass

\usepackage[utf8]{inputenc}

Now, I can actually use utf8.

In practice this is smoother with XeLaTeX, which will require some additional declarations in order to function as expected, which for some reason are not set per default.

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{mathspec}
\usepackage{xltxtra,xunicode}
% Fix incommensurability of font sizes which per default is awful
% this line must come after mathspec or fontspec
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\newcommand{\euro}{€}

This is not usually painful in modern LaTeX as such. However, the 💩 hits the fän if I try to use non-ascii ©haracters in BibTeX. I use BibLaTeX/biber instead. Sometimes a journal will advise against it but they don’t seem to notice if I ignore them, and it saves me much time.

### XeTeX

Everything just works AFAICT. It’s incompatible with a couple of primordial packages which do various fake unicode hacks (like the ucs package) but I don’t think those are actually needed anyway.

You can change fonts using

\setmainfont{Times New Roman}

But which fonts do you have? Find out manually.

fc-list : family

or, even more precise

fc-list :outline -f "%{family}\n"

PRO TIP: only load one of mathspec and fontspec because mathspec loads fontspec which causes errors.

A tonne may be isntalled

tlmgr install
mathdesign

#### unicode-math

If I decided to go hardcore unicode I could use unicode even for equations, via unicode-math.

With this package, changing maths fonts is as easy as changing text fonts — and there are more and more maths fonts appearing now. Maths input can also be simplified with Unicode since literal glyphs may be entered instead of control sequences in your document source.

Also if I were to copy-paste equations from a PDF generated by such means to LaTeX, they would be somewhat less mangled. The price is that it has certain quirks, e.g. missing some curly letters. Also, usually I do not typically have a choice of maths fonts because versions are stipulated in the style guide for the journal/conference/thesis I am writing. Therefore, while this is nifty, it adds burdens but brings insufficiently many benefits. The logic of collective action dictates I ignore it for now.

## Include LaTeX in python

Generating arbitrary LaTeX in python scripts, jupyter notebooks, Pweave literate documents? Use an ingenious python script called using latex_fragment to ease your burden and render your latex fragments inline. It was written by that paragon of coding cleanliness, that tireless crusader for not-dicking-around, me.

from IPython.display import display_latex, display
import latex_fragment
l = latex_fragment.LatexFragment(r'$$x=y$$')
display(l)

Note also that pandoc markdown already includes LaTeX support for LaTeX output.

Other options include inverting this setup, and including python in LaTeX via an executable notebook such as knitr.

## Make TeX run like a normal unix program

As opposed to the default, a pointless error-interaction-mode-that-briefly-seemed-useful-in-the-80s.

pdflatex -interaction=nonstopmode -halt-on-error

Bloody-minded-compile-my-document-at-all-costs-I-don’t-care-how-it-is-broken:

pdflatex -interaction=batchmode

## Putting dates in your drafts

I’m sure there must be a better way of doing this. Certain document classes (all?) have draft modes.

\documentclass[draft]{article}

A universal (not document-class-dependent) option was suggested by the Malaysian LaTeX User Group, Putting Dates in Watermarks:

\usepackage{draft watermark}
\usepackage{datetime2}
\SetWatermarkLightness{.9}
\SetWatermarkText{Draft\[email protected]\DTMnow}
\SetWatermarkScale{.3}

This may necessitate

tlmgr install draftwatermark everypage datetime2 etoolbox tracklang

## Spacing

Managing spacing is the major reason for existence for LaTeX. Thus is is curious how fragile and unintuitive it is. Here is a comprehensive guide to LaTeX spacing by Werner.

## Death-or-define macro

Death-or-define is how I think of the trick to force a macro definition redefinition even if there is no definition to be redefined – handy if I am rendering latex from some tricky source such as jupyter, or where I don’t have control over the overall document outside my section but don’t care about wreaking havoc on my collaborators; some other poor sap can deal with the macro mutation weirdness.

\providecommand{\foo}{}
\renewcommand{\foo}[1]{bar: #1}

hyperref is the command to support hyperlinks, clickable navigation of your document. This is fragile and must be loaded in a particular order. Beware.

## Emoji

There are two dominant ways to insert emoji into LaTeX.

You can try a dirty, shiny hack to include color emoji as images.

\documentclass{article}
\usepackage{coloremoji}
\begin{document}
Hello, 🌎.
\end{document}

Elegant but less colourful, XeTeX has native monochrome emoji via DejVu fonts.

\documentclass{article}
\usepackage{fontspec}

% these lines must come after fontspec
\newfontfamily\DejaSans{DejaVu Sans}
\newcommand\todo{{\color{red}\DejaSans 🚧}}

\begin{document}
\todo mention {\DejaSans 😁😂😃😇😉😈😋😍😱}
\end{document}

## Algorithms

Convention dictates explaining your algorithm with pseudocode. This obviates the problem of the uncertain semantics of particular programming languages, by replacing them with the semantics of no programming language at all.

There is a confusing profusion of options for doing this and they are all, IMO, inadequate, since none of them allow me to typeset higher order functions naturally, and that is an old and thoroughly mainstream idea. This means, for example, that it is hard to typeset automatic differentiation.

tl;dr: I use

• For formatting, algorithmicx + algpseudocode (a nice default syntax that comes with algorithmicx).
• inside an algorithm float.

### algorithmicx

How this looks:

\usepackage{algorithmicx}
\usepackage[noend]{algpseudocode}  % skip EndFor etc
\usepackage{algorithm}   % custom floats
\begin{algorithm}
\caption{Euclid’s algorithm}
\label{euclid}
\begin{algorithmic}[1] % The argument is the first line number
\Procedure{Euclid}{$$a,b$$} \Comment{The g.c.d. of a and b}
\State $$r\gets a \bmod b$$ \label{init}
\While{$$r\not=0$$} \Comment{We have the answer if r is 0}
\State $$a \gets b$$
\State $$b \gets r$$
\State $$r \gets a \bmod b$$
\EndWhile\label{euclidendwhile}
\State \textbf{return} $$b$$\Comment{The gcd is b}
\EndProcedure
\end{algorithmic}
\end{algorithm}

Algorithm line label references look like

\algref{euclid}{init}

If I am running minimalist TeX I need

tlmgr install algorithmicx algorithms

or I can do without algorithms if I do

\usepackage{float}
\newfloat{algorithm}{t}{lop}

Or perhaps I wish to typeset real code in a real language? minted enables this, allowing colour-highlighted math-enabled code rendering, bringing to LaTeX documents the conveniences that have been available to everyone else for some decades now.

There are alternatives.

### algorithms

algorithms provides algorithmic and an algorithm float, and seems to be fairly common and also fairly interchangeable with algorithmicx. Neither of these packages have been updated in a decade, so they are both suspicious, but they work OK.

This seems intermittently maintained but has better reference syntax, in that referring to a line number has no special syntax. It also seems to be preferred by IEEE.

TBD

### program

program does pseudocode formatting but with very different syntax and styling. It looks nice but I don’t use it as it’s less compatible with the other major players algorithmic so the odds of being able to copy and paste are low.

## IDs (ORCID, DOI etc)

AFAICT, at the basic level you create a hyperlink, e.g.

\href{https://orcid.org/0000-0001-6077-2684
}{Dan MacKinlay }

But what if I want the fancy logo so that everyone knows I cleverly did the ORCID thing? If I am using some benighted conference stylesheet from the 90s this is unlikely to work. But for a more modern situation (e.g. IEEE is usually current) I might be able to get an attractive green logo. I have made this work with the academicons package, which gets the logo via a custom font.

Then, for example ORCID is set up in the preamble:

\definecolor{orcidlogocol}{HTML}{A6CE39}

and in the body

\item \href{https://orcid.org/0000-0001-6077-2684
}{Dan MacKinlay \hspace{2mm} \textcolor{orcidlogocol}{\aiOrcid}  }

## Mathematical hacks

### Math size

I forget this all the time. Explained by overleaf, Math font size ordering is

\displaystyle       % Size for equations in display mode
\textstyle          % Size for equations in text mode
\scriptstyle        % Size for first sub/superscripts
\scriptscriptstyle  % Size for subsequent sub/superscripts

### Defining new operators

#### Without Limits

i.e. limits on the side, $${\mathop{\mathrm{sech}}\nolimits}^2 x.$$.

Plain style (works everywhere including old MathJax):

\newcommand{\sech}{\mathop{\mathrm{sech}}\nolimits}

amsmath style (works in AMSMath environments):

\DeclareMathOperator{\sech}{sech}

#### With Limits

i.e. limits underneath $${\mathop{\rm arg\,max}}_{x\to\infty} x$$.

plain style:

\newcommand{\sech}{\mathop{\rm sech}\limits}

amsmath style:

\DeclareMathOperator*{\argmin}{arg\,min}

## Diagrams

### SVG

Martin H says, on including SVG in TeX, that the smoothest route is to convert the SVG into PDF+tex, as per Johan Engelen’s manual:

inkscape -D -z --file=image.svg --export-pdf=image.pdf --export-latex

Then invoke using

\begin{figure}
\centering
\def\svgwidth{\columnwidth}   % sets width of next svg image
\input{image.pdf_tex}
\end{figure}

This can be automated using the svg tex package.

### PFGPlots

PGFPlots is a native diagramming/plotting package which supports PDF output.

## Editors

See LaTeX editors.

## Posters

a0poster is popular, as expounded by Morales de Luna, but I secretly feel that it sounds like a nightmare of legacy postscript nonsense and doesn’t even look good. sciposter is a popular a0poster variant.

tikzposter and beamerposter are both highlighted on sharelatex and are truly fugly. Why would anyone who claims to care about design inflict this on the world?

## IEEE style specialties

\begin{IEEEeqnarray}{rCl}Z&=&x_1 + x_2 + x_3 + x_4 + x_5 + x_6\IEEEnonumber\\&&+\:a + b%\end{IEEEeqnarray}