# LaΤeΧ

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

(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 deny the simple delight of the painstaking handicraft of manually setting line breaks, or who have grad students who will deal with all that shit for free. That is, a tool that meets the needs of that endangered animal, the Tenured Academic, 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, which is firm damnation.

Addendum: Yes, 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, and community support. However, standards lock-in being what it is, I believe I can avoid arranging the deckchairs on this sinking boat by waiting for incremental improvements to make a difference. I will discretely wait over here, near the lifeboats, for some amped-up scholarly version of Markdown to come save me and render the entire tiresome problem irrelevant.

## 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 fannish, upbeat and pious take by Graham Douglas, What’s in a name: a guide to the many flavours of Tex.

## Unicode

Put this at the start of every file you touch.

% !TEX encoding = UTF-8 Unicode

then after the documentclass

\usepackage[utf8x]{inputenc}

Then, actually use utf8.

This is not too painful in modern LaTeX. However, the 💩 will hit the fän if you try to use non-ascii ©haracters in BibTeX; don’t. Use BibLaTeX instead.

## 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}

## Include LaTeX in python

Generating arbitrary LaTeX in python scripts, jupyter notebooks, Pweave literate documents? Use an ingenious script called using latex_fragment. It was written by that paragon of coding cleanliness, by 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.

## Make TeX run like a normal unix program

As opposed to the default pointless-error-interaction-mode-that-briefly-thought-that-it-would-be-hip-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

Malaysian LaTeX User Group, Putting Dates in Watermarks

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

This may need

tlmgr install  draftwatermark everypage datetime2 etoolbox tracklang

You can skimp on the date info if you want but then the watermark is looooooong.

## Spacing

Managing spacing is th ewhole reason for existence for LaTeX, so of course it’s fragine, and unintuitive. 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 you are rendering latex from some tricky source such as jupyter, or where you don’t have control over the overall document outside your section but don’t care about wreaking havoc on your collaborators; some other poor sap can deal with the macro mutation weirdness.

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

## Algorithms / pseudocode / real code

Convention dictates explaining your algorithm with pseudocode. This remove 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 you to typeset higher order functions naturally, and that’s hardly a new idea.

tl;dr: use

• a hip markup such as

• algorithmicx + algpseudocode (a nice default syntax that comes with algorithmicx), or

• program

• inside an algorithm float.

\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage{algorithm}
\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$$
\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}

Are you running minimalist TeX? You’ll need

tlmgr install algorithmicx algorithms

or you can do without algorithms if you do

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

Or perhaps you 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.

## tlmgr

TeX has a packagemanager, tlmgr.

On Debian/Ubuntu it’s messed up. In addition to the basic system install, on Debian/Ubuntu you set it up via

tlmgr init-usertree

and possibly

sudo apt-get install xzdec

If that doesn’t work you might need alternate methods such as manual install. My current recommendation is to manually install if you want this; it’s a mess otherwise, since only supports releases for one year (and your Ubuntu distro is supported for much longer, so likelyhood is that you will rapidly find you ubutnu-supported texlive no longer compatible with your texlive-supported tlmgr)

## Minimalist TeX

MacTeX wastes your hard disk space if you install the whole gigantic thing. 5Gb for a 1980s typesetting system is cheeky, especially from people who delight in claiming that Microsoft Word is over-engineered, and that they are keeping it serious with their svelte, elegant, professional alternative. But LaTex is not “serious typesetting”, except in the sense that driving a panzer to work is “serious commuting”. (In this metaphor, Microsoft Word is some kind of polka-dotted clown car, as far as mathematics is concerned.)

However! You can install what you need via the tlmgr using the minimal distribution, basictex. Which is still hundreds of megabytes, but we are going to have to take what breaks we can here. Then you take the bare bones setup and install the extra things you need.

For example, to render jupyter notebooks, you’ll need:

tlmgr install \
collectbox \
collection-fontsrecommended \
enumitem \
logreq \
ucs \
xstring

To handle fancier jupyter notebook via ipypublish, we also need

tlmgr install \
latexmk \
translations

To handle biblatex:

tlmgr install biblatex

To handle modern referencing:

tlmgr install placeins \
todonotes \
chngcntr \
doi \
mdframed \
needspace \
cleveref
tlmgr install amsfonts \
amsmath \
lm \
unicode-math \
ifxetex \
ifluatex \
listings  \  # (if the --listings option is used)
fancyvrb \
longtable \
booktabs \
graphicx \
grffile \
xstring \
logreq \
biblatex \  # if biblatex is used
biber \  # if biber is used
fontspec \  # if xelatex or luatex
polyglossia  \  # if xelatex
xecjk \  # if xelatex
bidi   # if xelatex

To handle Anki flashcard rendering:

tlmgr install bbm-macros \
dvipng

To handle latex_fragment:

tlmgr install standalone \
preview

To handle .eps files.

tlmgr install epstopdf

To handle Tom Pollard’s markdown thesis:

tlmgr install truncate \
tocloft \
wallpaper \
morefloats \
sectsty \
siunitx \
threeparttable \
l3packages \
l3kernel \
l3experimental

You keep it up to date in a the obvious way:

tlmgr update --self
tlmgr update --all

The non-obvious thing is that this works for approximately one year, then you are cut off from updates, and have to do a crazy tedious procedure to get another year’s life out of TeX.

## No TeX at all

You just want equations? You don’t need TeX-the-software, just TeX-the-markup. Lots of things can render TeX math. In particular if you have an HTML or a markdown document with mathematical markup, many mathematical typesetting options are available. In fact, too many, all with incompatible syntax of course. The de facto standard is pandoc, which is what I usually use for turning my markdown+math into various documents (including, for example, parts of this blog).

### MathJax

MathJax allows you to put LaTeX equations online easily without bothering with the rest of that bullshit.

### KaTeX

Katex is a faster competitor to MathJax, but is not yet as widely supported. Katex even eliminated another pain point, having supported macros since 0.10.rc1. You couldn’t define macros inline which was tedious because macros are ubiquitous in real mathematics work. Now you can either inject them via config, or use the esoteric low-level \gdef to get LaTeX-like behaviour, since \renewcommand exists but doesn’t persist between equations, which makes it pointless for anything except prototyping individual macro definitions. KaTex support of math markup is not as complete as MathJax. In particular

• I miss the split environment.
• You can’t put math markup inside \text{}

### Inlined HTML mathematics

Both MathJax and KaTeX are eventually slow if you have enough equations in a document - MathJax sooner than KaTeX, but neither scales to the documents I write as a mathematician. You ideally want something different. There are a few attempts to do this.

bookish is a project by parser nerd Terrence Parr which, [like](https://github.com/parrt/bookish/blob/a1d94d372a375e897e3c58cd0951b8d57d665330/oldsrc/us/parr/bookish/translate/Tex2SVG.java] my latex_fragment, translates TeX markup to SVG, but in addition works out how to align the SVG with text correctly via herculean effort.

This approach is shared with Daan Leijen’s Madoko (introductory paper), which does math rendering in PDF or HTML as embedded SVG.

Both these last 2 projects took the unusual step of not using the de facto standard for markdown/academia, pandoc, in favour of implementing their own new engines.

Amazingly, despite pandoc already employing a somewhat obscure academic functional language (Haskell), Makodo chose an even obscurer academic functional language, koka. At least this one compiles to javascript, so I guess it’s not totally alien territory. Nonetheless… Anyway, it also includes some nifty publish-to-the-web features, and citation support, so maybe you don’t care about this obscurity.

There is another school of methods of rendering mathematics in HTML, which is the school who note that you can render MathJax without a browser using node.js, saving some time for the reader who need not mess around with a complicated post hoc multi-phase javascript-based rendering procedure. Presumably this could be implemented for KaTeX too. The tool du jour is MathJax-node-page which comes with a CLI mjpage which will pre-render HTML for you—it even claims to render math as SVG too, through forbidden magic into which it is best not to enquire too closely. See also mathmd. Wikipedia is aiming to leverage this approach via their mathoid project.

There are some full-pipeline tools which leverage this. The one that looks shiniest is ReLaXed, which also makes the case for their take on this approach

Many of us prefer markup languages (Markdown, LaTeX, etc.) to GUI document-editors like MS Office or Google Docs. This is because markup languages make it easier to quickly write documents in a consistent style.

However, Markdown is limited to the title/sections/paragraphs structure, and LaTeX has obscure syntax and errors that also make it difficult to stray from the beaten track.

On the other hand, web technologies have never looked so good.

• Beautiful CSS frameworks make sure your documents look clean and modern.
• There are JavaScript libraries for pretty much anything: plotting, highlight code, rendering equations…
• Millions of people (and growing) know how to use these.
• Shorthand languages like Pug and SCSS are finally making it fun to write HTML and CSS.
• (Headless) web browsers can easily turn web documents into PDF, on any platform.

ReLaXed is an attempt at finding the most comfortable way to leverage this for desktop PDF creation.

However, I need citations in my workflow, and it is not immediately clear how I would inject those into such an end-to-end solution, at least not without writing yet another plugin— however, possibly Zotero could help with its HTML citation reports or maybe one of the word processor plugins supports HTML documents? It merits investigation. Not by me.

### MathML

Native web rendering of mathematics is provided by MathML, but it is supported, more or less, only in Firefox, and also is an ugly syntax to write by hand. It’s more of a display backend for LaTeX math, or for some kind of equation editor. Unless this is more widely taken up I won’t be investigating it for my own use. In particular, I don’t know how fast it is, which is the major pain point with the javascript-based options. There are utils to convert LaTeX math to MathML, e.g. [Texzilla]https://github.com/fred-wang/TeXZilla), or LaTeXML, which I have not tried.

## Diagrams

How to include SVG in LaTeX. PGFPlots is a native diagramming/plotting package which supports PDF output.

## Editors

Why are there so many editors for LaTeX? They all seem reasonably interchangeable in terms of features. I just use whichever one I can remember the name of at the time.

Ideally I’d like easy TeX rendering from within my normal editor vs code but there are always weird friction points so I’ve given up on that for now.

### TeXshop

texshop is the open-source stalwart editor on macOs. It makes reasonable progress towards being intuitive. Its name is in my muscle memory.

### TeXWorks

The TeXWorks project is an effort to build a simple TeX front-end program (working environment) that will be available for all today’s major desktop operating systems—in particular, MS Windows (7/8/8.1/10), typical GNU/Linux distros and other X11-based systems, as well as Mac OS X. It is deliberately modeled on Dick Koch’s award-winning TeXShop for Mac OS X, which is credited with a resurgence of TeX usage on the Mac platform.

It’s minimalist, shipping without a billion typesetting macros, which is both a plus and a minus. I like minimalist, but also I don’t want to have to remember every bloody latex command.

Bizarre bonus feature: you can script it using javascript.

### TeXStudio

TeXStudio is an integrated writing environment for creating LaTeX documents. Our goal is to make writing LaTeX as easy and comfortable as possible. Therefore TeXstudio has numerous features like syntax-highlighting, integrated viewer, reference checking and various assistants. For more details see the features.

TeXstudio is open source and is available for all major operating systems.

Fun fact: This was forked from TexMaker ten years ago.

TexStudio has a million features. The UI is an exercise in brutalist maximalism and excessive featuritis, but it does do more or less everything you want. Many LaTeX macros, which is handy. Also heaps of stuff you will never want and wish would stop crowding your menu? Extensive built-in SVN support? yep.

Amazing feature: has image drag-n-drop support.

### TexMaker

Tex Maker is a free, modern and cross-platform LaTeX editor for linux, macosx and windows systems that integrates many tools needed to develop documents with LaTeX, in just one application. Texmaker includes unicode support, spell checking, auto-completion, code folding and a built-in pdf viewer with synctex support and continuous view mode. Texmaker is easy to use and to configure. Texmaker is released under the GPL license.

### VS Code

latex-workshop is the VS Code LaTeX extension. It’s got a lot of features but ends up being confusing when things go wrong.

### Atom

atom-latex and the atom latex package both bring LaTeX support to the Atom editor though I haven’t yet worked out the difference. The latter supports literate coding so is morally superior.

### Mathematica

Mathematica can export mathematics to TeX and is a good, if colossally overengineered, editor for equations. It has the bonus power to automate many tedious steps of working.

### LyX

LyX is a document processor that encourages an approach to writing based on the structure of your documents (WYSIWYM) and not simply their appearance (WYSIWYG).

LyX combines the power and flexibility of TeX/LaTeX with the ease of use of a graphical interface. This results in world-class support for creation of mathematical content (via a fully integrated equation editor) and structured documents like academic articles, theses, and books. In addition, staples of scientific authoring such as reference list and index creation come standard.

This graphical editor thing is a noble goal but TBH not my top priority.

### TeXmacs

TeXmacs is another WYSIWYM thing – if you want to integrate a beautiful but obscure and irregularly maintained notebook-style interface with your typesetting. Some do.

Once again, I’d rather use knitr etc for integrating my diagrams and keep the GUIs separate, but this is personal preference.

## 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?