TUGboat, Volume 41 (2020), No. 1
TEX, LATEX and math
Enrico Gregorio
Abstract
We discuss some aspects of mathematical typesetting: choice of symbols, code abstraction, fine details.
Relationships between math typesetting and international standards are examined. A final section on
typesetting of numbers and units reports on somerecent developments in the field.
1

Introduction

Readers may well know that TEX was born out of
Knuth’s discomfort after having seen the proofs of
the new edition of the first volume of his magnum
opus “The Art of Computer Programming”.
Many papers have been written by Knuth himself and by others on the topic of math typesetting.
Here I’d like to present some personal ideas on thesubject, coming from almost thirty years of experience in mathematical typesetting. I’ll also present
some recent developments and new tricks made available with expl3.
2

A very short lead-in to math in TEX

Every TEX guru knows that TEX is (almost) always
in one of three modes:• horizontal mode,• vertical mode,• math mode.
Except for circumstances when TEX is in no mode atall (when writing to external files, for the curious).
Each mode comes into two flavors, but here weare interested only in math mode. Knuth calls thetwo flavors ‘math mode’ and ‘display math mode’.
In order to better distinguish between them, I’ll callthe former ‘inline math mode’, so the unadorned‘math mode’ will denote both.
There are subtle, well, not so much so, differences between P
the two flavors; beginners
are most
n1
12
impressed by
k
=
n
n
+
(n
+
1) thatk=1
32
suddenly becomes


n
X
1
1
2
k = n n+(n + 1)3
2
k=1

when displayed and a very common question is ‘how
do I get the limits above and below the summation
symbol and real fractions, not that smallish replacement symbol?’
Like all of us, I’ve been a beginner myself; I
discovered \limits and abused it. Penitenziagite,
First published in ArsTEXnica 28 (Oct 2019), pp. 47–57.
Reprinted with permission.

43
would have said Salvatore in “Il nome della rosa”(Umberto Eco’s novel; the English title is “The nameof the Rose”). Now I’m no longer a beginner andknow why \limits should not be used; and let’s
not talk about the dreaded \displaystyle that issometimes suggested to newbies. The proper way isjust \sum.
To the contrary, beginners are usually much lessimpressed by the wrong typesetting in
A\B = {x|x ∈ A, x ∈/ B}
but they are likely to shrug and move on, if they evernote it. Sometimes they see something’s wrong and‘fix’ the vertical bar by using \,|\, that’s still wrong.
Why is it wrong? The spacing is too small, of course,
but there’s more to the problem: two appearancesof such a construction in the same document is asin similar to what I describe to young basketballreferees: “whoever calls a double foul during theircareer has called one too many”. The correct answer
is: first of all define a macro for the object, forinstance,\newcommand{\suchthat}{\,|\,}(I’m talking LATEX, plain TEX users can translate).
In case one asks, if a+b appears twice or more in adocument there’s no need to make a macro out of it;
the separator in the set builder notation is a single
conceptual object and so it must be typed by a single
command.
About the spacing, one should realize that thereverse bar is a binary operation symbol and thevertical bar is a relation symbol. Both are alreadydefined in all flavors of TEX and they are, respectively,\setminus and \mid, but it’s still convenient andlogically sound to define \suchthat, because \midis a ‘generic’ name:\newcommand{\suchthat}{\mid}...
A \setminus B=\{x \suchthatx\in A, x\notin B\}
will typeset as
A \ B = {x | x ∈ A, x ∈/ B}while this is the version with the thin spaces:
A \ B = {x | x ∈ A, x ∈/ B}Compare closely the spaces around the vertical bar.
I’m not saying the last realization should be
rejected as awfully wrong: personal judgment is always welcome when typography is concerned, after
having studied the alternatives and common practice.
Above all, consistency throughout a document is amust. I had to edit a paper where the separator wasa bar or a colon or a semicolon, depending on which
TEX, LATEX and math44

TUGboat, Volume 41 (2020), No. 1of the three authors had typed the formula. Defining\suchthat allows for delaying any decision about
what symbol to use until the last minute. More on
set builder notation later.
The TEXbook lists several symbol names, somehave semantics attached to them, like \setminus,
and others don’t, like \mid or \otimes.1 Why isthat? Some symbols have essentially a single use case,others appear in different branches of mathematics
with different meanings. Everybody loves \lhd and\unlhd, right? The symbols typeset as C and E
respectively. I believe to have seen once what thenames should suggest, but I forgot it. The symbols
are common in group theory, where they denote‘normal subgroup’: it’s heartily recommended togroup theorists to define a meaningful command forthem. Oh, I was almost forgetting! Those are notdefined as relation symbols in LATEX, so a savvy
group theorist will type in the document preamble% normal subgroup\newcommand{\ns}{\mathrel\lhd}\newcommand{\nseq}{\mathrel\unlhd}% subnormal subgroup\newcommand{\sns}{\ns\ns}
The symbols are not among the core ones designed
by Knuth. They first appeared in a symbol font
distributed along with LATEX; possibly Lamport usedthem for his own papers as binary operators andthe classification stuck. They were later included inamssymb (\vartriangleleft, which is a relation).
What should an author do? The case of normal
subgroups is clear: I surely wouldn’t litter my paper with \mathrel\lhd each time I want to mention
normal subgroups. However, suppose a paper frequently uses Euler’s totient function, which has thewell established tradition of being denoted by ϕ (theopen version of phi). Is it better to use \varphi or
to define \euphi? The latter. Imagine that upon receiving proofs, the author realizes that all instancesof \varphi print out φ, because the publisher uses afont that lacks the proper symbol. With \euphi it isa matter of doing a redefinition, probably borrowing
the open phi from another font. We don’t know when
the instruction \let\varphi=\phi is performed, butusing \euphi makes this irrelevant.
An important exception: in the abstract there
should be no use of personal macros. It should be
able to typeset with a ‘naked’ version of LATEX: it’svery common nowadays that the abstract is fed tosome web page that maybe uses MathML, MathJax
or similar device for handing the text to browsers.
1 Generally L
AT X kept the same names.

E

Enrico Gregorio

Going back to the normal subgroup symbol, one
should know that every math symbol belongs to aclass and there are seven of them:• class 0, ordinary symbols;• class 1, operators;• class 2, binary operations;• class 3, binary relations;• class 4, opening symbols;• class 5, closing symbols;• class 6, punctuation.
TEX will set the spacing between symbols according
to well defined rules. This is not the place to discussthem fully, see [4]. Any object, as long as it is legal
in math mode, can be defined to behave as if it
belongs in one of the above classes by typing it as
the argument to\mathord \mathop \mathbin \mathrel\mathopen \mathclose \mathpunct
For instance, the symbol for the determinant is internally carried out (in LATEX) by something like\mathop{\operator@font det}\nolimits
but there is a higher level interface available fordeclaring new symbols like this; for instance, one
does\DeclareMathOperator{\adj}{adj}in order to introduce a symbol for the adjugate matrix. A one-shot operator can be typeset in the
document by\operatorname{adj}The *-version of both commands makes for a symbolthat carries limits above and below in display mathmode, on the side when inline.
The unfortunately common perversion of denoting open intervals like ]a, b[ needs input such as\mathopen]a,b\mathclose[
One can easily spot that something is wrong whenjust using ]a,b[ by looking at the difference between
the two instances below
x ∈]a, b[x ∈ ]a, b[
In my calculus notes I type \interval[o]{a,b}, so
I can decide to be a perv by just changing a few lines
in the definition. An open interval will be typeset as(a . . b), but I’m not bound in any way: I can go backto the comma again by just changing a line. Also, I
like to write upper unbounded intervals like (a . . →),but I use \pinf for the arrow, so I can make it to be
typeset ∞ by acting on a single line, should I change
my mind.
Upon entering math mode, TEX will constructa math list consisting of math atoms, each of which

TUGboat, Volume 41 (2020), No. 1

 6
a + 2a3 b3 + b6 = q 2
4a3 b3 = − 4 p327
 33
a + b = −q

a6 − 2a3 b3 + b6 = q 2 + 4 p3
27
 3
a + b3 = −q(a3 − b3 )2 = q 2 + 4 p3
27
33
a + b = −q

r
4 3
3
3

a − b = q 2 +
p
27

45

( 6
a + 2a3 b3 + b6 = q 2

4 3
p
27
(
a3 + b3 = −q
4 3
a6 − 2a3 b3 + b6 = q 2 +p27(
a3 + b3 = −q
4 3
(a3 − b3 )2 = q 2 +
p
27
 3
−q
a + b3 = r
4 3
a3 − b3 = q 2 +p
27
4a3 b3 = − a6 + 2a3 b3 + b6 = q 2

4a3 b3 = −

4 3
p
27

a3 + b3 = −q

4 3
 a6 − 2a3 b3 + b6 = q 2 +p27
a3 + b3 = −q4 3
(a3 − b3 )2 = q 2 +p27

a3 + b3 = −q

r
4 3
3
3

a − b = q2 +p
27

Figure 1: Three ways of laying out the derivation of Cardano’s formula( 6
a + 2a3 b3 + b6 = q 2

4
4a b = − p327(
a3 + b3 = −q
4 3
a6 − 2a3 b3 + b6 = q 2 +p27(
a3 + b3 = −q4 3
p(a3 − b3 )2 = q 2 +27
 3
 a + b3 = −q
r
4 3
3
3
 a − b = q2 +
p
27
3 3

Figure 2: One of the worst alignments I can conceive

has a nucleus, a subscript field and a superscript
field. When exiting from math mode, the math list
will be transformed into a horizontal list according
to the (complex) rules described in Appendix Gof The TEXbook. These rules add spaces, as said
before, but also take care of the bidimensionality ofmath formulas: superscripts, subscripts, fractions,accents, radicals, extensible delimiters and many
more aspects.
Had Knuth been into theoretical physics, heprobably would have added also “prescripts” for isotopes and staggered multiple subscripts and superscripts for tensors. Unfortunately he hasn’t. Seelater for more on this topic.
3

Fine points of mathematics typing

The title is the same as chapter 18 in The TEXbook.
Of course I won’t go through Knuth’s words. Since
I’m talking LATEX and math, I assume that amsmath
is loaded: no serious math typesetting can be done
without it.

A point that’s not touched upon in the TEXbook
is ‘when, really, consecutive equations should bealigned and where’. Browsing TEX.StackExchange
reveals several examples of bad alignments.
A prominent example is a derivation of Cardano’s formula2 which I won’t give the code for, butjust three realizations that you can see in figure 1.
I often use the style “the good, the bad, and theugly”. There is actually an even uglier way, which iswhat the questioner was asking for, see figure 2.
What’s the problem? The equals signs are notreally related to one another. The pairs of formulas
are related, but the fact that they are equations is almost irrelevant. Mixing ragged right and ragged leftin one and the same paragraph (or display) makesfor very hard reading. I’d instead be more generous
with vertical spacing between the various braces andI have no doubt whatsoever that the leftmost realization is our Clint Eastwood. Look for holes in thetypeset output and remove them.
Another example can be seen in figure 3.3 You
can judge for yourself which is the best way to present
the display. My opinion is that the equals signs inthe second column pair are not related to each other,so they’re not to be aligned.
Linear systems are an exception, because theirmatrix-like structure is more important than holes. I
recommend the wonderful systeme package by Christian Tellechea [11]. No doubt there are other exceptions: typography, and mathematical typography inparticular, is a craft that doesn’t obey mechanicalrules. A thin space may open up symbols and makethem easier to read, adding a pair of parentheses
may clear up an ambiguity, removing unnecessary
2 https://tex.stackexchange.com/questions/193581
3 https://tex.stackexchange.com/questions/500472

TEX, LATEX and math

46

TUGboat, Volume 41 (2020), No. 1


 
Aµ
Aµ
cos θ − sin θ
→
,
ρ∗µ
ρ∗µ
sin θ
cos θ
 
 

ψL
ψL
cos ϕψL − sin ϕψL→,χL
sin ϕψLcos ϕψL
χL
 
 

cos ϕψ̃R − sin ϕψ̃R
ψ̃R
ψ̃R
,
→
sin ϕψ̃R
cos ϕψ̃R
χ̃R
χ̃R
 

 
Aµ
Aµ
cos θ − sin θ
→
,
ρ∗µ
ρ∗µ
sin θ
cos θ
 
 

ψL
ψL
cos ϕψL − sin ϕψL→,χL
sin ϕψLcos ϕψL
χL
 
 

cos ϕψ̃R − sin ϕψ̃R
ψ̃R
ψ̃R
,
→
sin ϕψ̃R
cos ϕψ̃R
χ̃R
χ̃R


gel
g∗
∆
tan ϕψL =m˜∆tan ϕψ̃R =m̃tan θ =tan θ =gelg∗tan ϕψL =tan ϕψ̃R =

(1)
(2)
(3)
(4)

∆
m
˜
∆
m̃

(5)
(6)

Figure 3: Two similar alignments

parentheses may improve the quality of a formula.
Compare top and bottom linef (x + h) − f (x)g(x + h) − g(x)+bhhf (x + h) − f (x)g(x + h) − g(x)a+bhhand decide which one looks better. In my notes I used
the bottom one when working the proof of linearity ofthe√ derivative. If I talk about “the function g(z) =z − 1 ”, I add a thin space before ending inline
math mode:a‘‘the function $g(z)=\sqrt{z-1}\,$’’in order to avoid the clash between the√ vinculum
and the quotes in “the function g(z) = z − 1”. Try
with a parenthesis
after the radical
to see another√√case: (1 + 2)−1 versus (1 + 2 )−1 . In the lattercase a thin space has been added.
Going to very fine details: does anybody notice
the differences below? Consider the formulas
log |x| =6 log|x|(7)| sin x| =6 |sin x|(8)

k adj Ak =6 kadj Ak(9)

where the questionable typesetting is on the left.
While the top left could be a typographic choice (solong as it is consistent), the other formulas in theleft-hand sides are definitely wrong.
The mathtools package provides a very goodfacility for handling these cases, namely\DeclarePairedDelimiter{\abs}{|}{|}
that allows to type \abs{\sin x} and forget about
the dreaded thin space, which can also be avoided
by\lvert\sin x\rvert
Enrico Gregorio

Which style to choose is a matter of personal preference and habit. I recommend not to abuse thefacility: reserve it for functions such as absolute values, norms and similar objects. Don’t exploit it forparenthesized expressions: something like\paren{a+b}\paren{a-b}=aˆ2-bˆ2hinders input reading and would print the same as(a+b)(a-b)=aˆ2-bˆ2. True, one could do\paren[\big]{a\paren{b+c}}
but is this really more legible than\bigl( a (b + c) \bigr)
that keeps the usual mathematical structure? Thatis, assuming \big size is really necessary, which it
isn’t in the particular case.
Since I mentioned trigonometric functions, lookat√√√
sin x + cos x + tan x
and explain what’s going wrong. Yes, the tittle makes
the difference! It makes ‘sin’ higher than ‘cos’ andmoves up the radical sign; similarly with ‘tan’. In
my trigonometry notes I have\let\cos\undefined\DeclareMathOperator{\cos}{cos\vphantom{i}}\let\tan\undefined\DeclareMathOperator{\tan}{tan\vphantom{i}}with which the above formula would become√√√
sin x + cos x + tan x
Radicals often need fine control in order to get themaligned with each other. Some appropriate trick
involving \vphantom or \smash can fix things up:√√√√
x + y 6= x + y

TUGboat, Volume 41 (2020), No. 1
Again, left is the questionable output; the formulaon the right has been input as\sqrt{x}+\sqrt{\smash[b]{y}}The alternative\sqrt{\mathstrut x}+\sqrt{\mathstrut y}ppdoesn’t seem as attractive:x + y. Radicals
would need a full chapter, so I’ll stop here, except
for one last thing: add a thin space when a radical
is followed by a fence; similarly, add a thin spacewhen a big operator (summation, product, integral)in display math mode is preceded by a fence and its
limits are wide. Example:
X
 X

n
n
ak 6=
ak
k=1

4

k=1

Upright or italic?

Rivers of (electronic) ink have been spilled trying
to answer the question. Actually it cannot be answered: mathematicians and engineers agree to disagree. Physicists disagree with each other.
Part of the question is: should constants be
typeset in an upright font or not? The ISO 800002:2009 standard prescribes upright; adhering to thisstandard is mandatory in some technology and commercial fields. This is a good thing: people reading atechnical report or manual will have no doubt about
the meaning of a symbol.4 While I strongly disagreewith several decisions of the ISO standard, on mathematical grounds, I accept the underlying philosophy
towards uniformity in the technical fields. Surely
I appreciate its ban on the mathematically wrong
sin−1 and similar: the standard has disputable aspects, but it’s never wrong from a mathematicalpoint of view.
On the other hand, many mathematicians are
traditionalists and prefer italics for constants suchas e (the Euler number) and i (the imaginary unit).
Euler and Gauss used italics for the latter, and I’mamong those who don’t dare to challenge their authority. Of course, I know that mathematical notation
has changed along time. I’d not use Cayley’s original
notation for matrices5 because a better notation has
developed. I follow the practice of setting standard
function names in upright type (sine, cosine, logarithm and so on) even when ancient mathematicians
didn’t.
However, such decrees as ‘symbols for vectors
should be bold italic serif lowercase, for matrices
should be bold italic serif uppercase, for tensors
4 A problem with ISO standards is that they have to bebought; the one we’re talking about prices 158 CHF, about
143 e or $160 at the current exchange rate.
5 https://tex.stackexchange.com/q/487643

47should be bold italic sans serif uppercase’ make mesmile: as a mathematician, I know that vectors,
matrices and tensors are not different objects froma mathematical point of view. Matrices admit aneasier two-dimensional representation: this is the‘big’ difference.
For pedagogical reasons, I might use distinctive
typesetting for vectors and matrices in a students’
textbook. In a research paper or graduate levelbook I’d probably not make any distinction, if not
mandated by clarity. In this case I’d explain thenotation choices at the beginning of the paper orbook.
A very fine book by J. Dieudonné [2], in the
English edition by Academic Press, uses
• R or C for number sets,• X for manifolds, E for vector bundles,• A for vector space operators,• Tx (X) or Tx (f ) for the tangent space or linear
mapping,• dx f or dx f for the differential at x of a mapping(vector valued or scalar valued),• Z for tensor fields,
and several other conventions that are consistently
followed across the book and the series. The bookstarts off with a nine page long notation section. The
same notation is used in the original French version.
However, it happens that book translations use
different conventions from the original. It is thecase for W. Rudin’s ‘Real and Complex Analysis’ [9]where the differential ‘d’ is in italics, whereas it’s
upright in the Italian translation published by BollatiBoringhieri [10]. I disagree with the publisher: maybe
the editorial preference is for the upright ‘d’, but theauthor’s style should be preserved as much as possible.
Not a big deal, one could think. No, this reflects
on the meaning of the differential ‘d‘. There are several arguments in favor or against italics; my feelingis that most pure mathematicians prefer italics.
By the way, how to input the symbol in sucha way that the convention can be changed at will?
The simplest and more effective way is to define\newcommand{\diff}{\mathop{}\!d}(or \mathrm{d} if one must have the abomination).
I believe I learned this from Claudio Beccarithrough a comp.text.tex post. The code was credited to him in the paper [5],6 but I’m not sure about
the real source of this code pearl. Claudio Beccari
had earlier proposed much more complicated code [1],namely6 The paper is also available in English [6].

TEX, LATEX and math

48

TUGboat, Volume 41 (2020), No. 1\makeatletter\providecommand*{\diff}{%\@ifnextcharˆ{\DIfF}{\DIfFˆ{}}%}\makeatother\def\DIfFˆ#1{%\mathop{\mathrm{\mathstrut d}}%\nolimitsˆ{#1}%\gobblespace}\def\gobblespace{%\futurelet\diffarg\opspace}\def\opspace{%\let\DiffSpace\!%\ifx\diffarg(%\let\DiffSpace\relax\else\ifx\diffarg[%\let\DiffSpace\relax\else\ifx\diffarg\{%\let\DiffSpace\relax
\fi
\fi
\fi
\DiffSpace}
What’s the idea in the complicated definition? Look
whether a superscript follows; if it doesn’t, add adummy one. Well, this is already wrong, because it
adds \scriptspace unconditionally. After that, thenext token is examined: if it is a fence, then don’t
add \!, because a \mathop is followed by a fence withno thin space; in case an ordinary symbol follows, the\mathop would add a thin space, which is removed
by \!. Well, try it with \diff\bigl(x+y\bigr).
Next try the simpler definition and see! Where’s thetrick? The empty \mathop is followed by an ordinary
symbol, the ‘d’; we just need to remove the excess
thin space! The thin space preceding the empty\mathop is inserted automatically by TEX following
the rules. Thus we can define\newcommand{\tder}[2]{\frac{\diff #1}{\diff #2}}
without worrying that spurious spaces may creep in.
Instead\iint\limits_{D} f(x,y) \diff x \diff ywill typeset as neededZZ
f (x, y) dx dyDEnrico Gregorio

For differential forms
f (x, y) dx ∧ dy
the spacing will be automatically right.
The same paper by Claudio [1] proposes commands for the constants, namely% The number ‘e’\providecommand*{\eu}{\ensuremath{\mathrm{e}}}% The imaginary unit
\providecommand*{\iu}{\ensuremath{\mathrm{j}}}I strongly disagree with proposing \ensuremath; referring in the text to the Euler’s number by
We use \eu\ to denote...
is by no means easier and clearer than
We use $\eu$ to denote...
One keystroke more? So what? That’s a mathematical symbol so it ought to be typed in math mode,
just like when we talk about the variable x. My
definition would be\newcommand{\eu}{\mathord{e}}so typing \eu outside of math mode would raise anerror. Change to \mathrm if you prefer upright type.
During the preparation of this paper, I examined
the toptesi bundle, to find\providecommand{\eu}{%\ensuremath{%{\mathop{\mathrm{e}}\nolimits}%}%}
This is disputable in several respects:• \ensuremath serves no real purpose;• \nolimits can be safely omitted, because the\mathop{...} bit is followed by }, so surely
there are no limits to take into account;• \mathop itself is redundant, because the wholething is braced, so it is treated as an ordinary
symbol.
Oh, wait! No, \mathop is actually wrong! Consider
the following code:\documentclass{standalone}\usepackage{amsmath}\newcommand{\euA}{\mathrm{e}}\newcommand{\euB}{%\ensuremath{%{\mathop{\mathrm{e}}\nolimits}%}%}\begin{document}$2\euA\euB$\end{document}

TUGboat, Volume 41 (2020), No. 1
The output is shown in figure 4. Do you see theproblem? A single character in the argument to\mathop is raised or lowered so that it extends thesame distance above and below the math axis.

2eeFigure 4: Magnified output for the Euler’s constantproblem

Now that we’re on the spot, how to define abetter \tder macro also supporting higher orderderivatives? The first attempt,\newcommand{\tder}[3][]{%\frac{\diffˆ{#1}#2}{\diff #3ˆ{#1}}%}
has a flaw: it unconditionally adds \scriptspace toboth the numerator and denominator. If I measure
the width of \tder{f}{t} in display math mode,with the standard fonts and document class, I get
14.07712pt; the version without the dummy exponents has width 11.91045pt. More than two points!
With the upright ‘d’, the difference would be half apoint. And the visual result shows more:
df
df
df
df
6=
6=
dt
dt
dt
dt
Yes, we need to avoid the dummy superscript, alsowith the upright ‘d’, although the difference is lessnoticeable: we want perfect output, don’t we? Andwe want macros that allow users to choose their own
preferred ‘d’. One could test whether the argument
is empty, but there’s a better way with xparse:\NewDocumentCommand{\tder}{s o m m}{%\IfBooleanTF{#1}{\dfrac}{\frac}%{\diff\IfValueT{#2}{ˆ{#2}}#3}% num{\diff #4\IfValueT{#2}{ˆ{#2}}}% den}
The *-version delivers \dfrac (just in case one needsit), otherwise \frac is used. The numerator and thedenominator add the exponent only if the optional
argument is specifically used. Thus \tder{f}{t}will not add a dummy exponent.
5Sets, bras and kets

A short note on the title. Physicists have a sense ofhumor: a well-established notation for inner products
is hx | yi, called a “bracket”. A mathematician would
denote the linear or semilinear forms induced by thebracket as hx | −i and h− | yi. Physicists, instead,use hx| for the former and |yi for the latter, callingthem “bra” and “ket”.
For several years, LATEX has been requiring eTEX extensions, among which \middle is a very

49
useful one. For instance, we can typeset18x∈R − ≤x≤2
5with no phantom and no null delimiter. On the other
hand, the code
\left\{x\in\mathbf{R} \;\middle|\;-\frac{1}{2}\le x\le \frac{8}{5}\right\}
is still really ugly and something like\set*{x\in\mathbf{R}\suchthat-\frac{1}{2}\le x\le \frac{8}{5}}would be much nicer. We call xparse and expl3 to
the rescue!
\documentclass[varwidth]{standalone}\usepackage{amsmath}\usepackage{xparse}\ExplSyntaxOn\NewDocumentCommand{\set}{som}{% limit the scope for \suchthat\group_begin:\cs_set_protected:Npn \suchthat{\tl_use:N \l__egreg_set_st_tl}\IfBooleanTF{#1}{\egreg_set_auto:n { #3 }}{\egreg_set_fixed:nn { #2 } { #3 }}\group_end:}\tl_new:N \l__egreg_set_st_tl\cs_new_protected:Nn \__egreg_set_st:n{\tl_set:Nn \l__egreg_set_st_tl { #1 }}\cs_new_protected:Nn \egreg_set_auto:n{\__egreg_set_st:n{\nonscript\;\middle\vert\nonscript\;}\left\{ #1 \right\}}\cs_new_protected:Nn \egreg_set_fixed:nn{\tl_if_novalue:nTF { #1 }TEX, LATEX and math

50

TUGboat, Volume 41 (2020), No. 1{\__egreg_set_st:n { \mid }\lbrace #2 \rbrace}{\__egreg_set_st:n{ \mathrel{#1\vert} }\mathopen{#1\lbrace}#2\mathclose{#1\rbrace}}}\ExplSyntaxOff\begin{document}$\set{a,b,c}\cup\set[\big]{a,b,c}$$\set{x\suchthat a<x<b}$$\set[\Big]{x\suchthat a<x<b}$$\set*{x\suchthat \dfrac{1}{2}<x<3}$\end{document}

The idea is to use a syntax familiar from mathtools’\DeclarePairedDelimiter. The output is in figure 5.
{a, b, c} ∪ a, b, c{xn | a < x < b}ox a<x<b


1
x
<x<3
2

Figure 5: Examples of set notation

In The TEXbook, Knuth recommends to add
thin spaces when the set builder notation contains abar, that is, it is not just a list of elements. I disagree,
but how could it be implemented? It’s possible tolook for the presence of \suchthat at the outer level
and, in this case, to add the thin spaces at either
end; nested sets would examine their own contents
for the presence at the outer level.
A full implementation would also feature thechoice for the delimiter as a preamble setting. I
leave this as an exercise for whoever wants to makea package out of this code.
There is some duplication in the code below,
but it’s unavoidable. The reason is that using an
O{} specifier for the optional argument would allow \mathclose{#2\rbrace} and no case distinction. However, one can see the difference if a subscript is added\rbrace_{1} \mathclose{\rbrace}_{1}}1}1Enrico Gregorio

Different coding is possible, though. It would not bedifficult to allow | instead of \suchthat. Look at
how the macros for bras and kets can be defined.
\documentclass[varwidth]{standalone}\usepackage{amsmath}\usepackage{xparse}\NewDocumentCommand{\bra}{som}{%\IfBooleanTF{#1}{\left\langle #3 \right|}{%\IfNoValueTF{#2}{\langle#3\mathclose|}{\mathopen{#2\langle}#3\mathclose{#2|}}%}}\NewDocumentCommand{\ket}{som}{%\IfBooleanTF{#1}{\left| #3 \right\rangle}, {%\IfNoValueTF{#2}{\mathopen|#3\rangle}{\mathopen{#2|}#3\mathclose{#2\rangle}}%}}\NewDocumentCommand{\braket}{som}{%\IfBooleanTF{#1}{\extensiblebraket{#3}}{\fixedbraket{#2}{#3}}%}\ExplSyntaxOn\NewDocumentCommand{\extensiblebraket}{m}{\group_begin:\char_set_active_eq:nN { ‘| } \egreg_bar_auto:\mathcode‘|="8000 \scan_stop:\left\langle#1\right\rangle\group_end:}\NewDocumentCommand{\fixedbraket}{mm}{\group_begin:\char_set_active_eq:nN{ ‘| }% active char is |\egreg_bar_fixed: % equal to\mathcode‘|="8000 \scan_stop:\IfNoValueTF{#1}{ \egreg_braket:n { #2 } }{ \egreg_braket:nn { #1 } { #2 } }\group_end:}\cs_new_protected:Nn \egreg_bar_auto:

TUGboat, Volume 41 (2020), No. 1{\nonscript\,\middle\vert\nonscript\,}\cs_new_protected:Nn \egreg_bar_fixed:{\mathinner{\egreg_size: \vert}}\cs_new_protected:Nn \egreg_braket:n{\cs_set_protected:Nn \egreg_size: { }\langle #1 \rangle}\cs_new_protected:Nn \egreg_braket:nn{\cs_set_protected:Nn \egreg_size: { #1 }\mathopen{\egreg_size: \langle}#2\mathclose{\egreg_size: \rangle}}\ExplSyntaxOff

51
their mathematical meaning (and not, say, as page
markers).
When a number appears in text and is mentioned as a mathematical object is should be input
inside a math formula:a vector space of dimension˜$5$
But what about large numbers that need to be split
in smaller units for readability? For instance, can you
spell out 7400043022221 without first counting how
many digits the number has? Isn’t 7 400 043 022 221
easier to parse? Possibly not for an American who’s
more accustomed to 7,400,043,022,221 (and probably
would be at stake when people talks about meters
and liters).
Now let’s suppose your scientific paper has several tables with numeric data and you’re not sure
about the editorial policy of the journal to which
you’re submitting it. Will the journal require American style or prefer thin spaces for grouping digits?

\begin{document}$\bra{x}\quad\ket{x}$$\braket{x|y}$$\braket[\Big]{x|y|z}$$\braket*{a|b}$$\braket[\Big]{a|b|\dfrac{c}{d}}$$\braket*{a|b|\dfrac{c}{d}}$\end{document}

I’ll not comment the code, except for mentioning
how easy is to define the value of a character when
it will be made active (math active, in this case).
hx| |xihx
D | yi Ex y z

ha
D | bi c E
a b
dE
D
c
a b
d
Figure 6: Examples of bras and kets

6

Numbers and units

How should numbers be typed in the LATEX document? Knuth himself once acknowledged that his
usual practice is not very good and realized it whenwriting “Concrete Mathematics” [3], were numbers
are typeset with the Euler font when they’re used inTable 1: Tables with different formatting options
for numbers (Source: Mr Leporello, private
communication)

NationNumberNationNumber

Italy
Germany
FranceTurkeySpain

640 375
231 803
100 00291 3291 003 000

Italy
Germany
FranceTurkeySpain

640,375
231,803
100,002
91,3291,003,000

Let’s consider the two tables in table 1. They
are typeset with exactly the same input, namely\begin{tabular}{@{}l
S[table-format=7.0]@{}}\toprule
Nation & {Number} \\\midrule
Italy& 640375 \\Germany & 231803 \\France & 100002 \\Turkey &91329 \\
Spain
& 1003000 \\\bottomrule\end{tabular}
and it’s siunitx [12] doing all the magic. Of course
there is a catch: just before the second copy of thetable I added\sisetup{group-separator={,}}TEX, LATEX and math

52

TUGboat, Volume 41 (2020), No. 1

I could have added the option also in the bracketedargument to the S column, which is one of the facilities made available by the package. Similarly,
the big number above has been typeset first with\num{7400043022221} and then with\num[group-separator={,}]{7400043022221}
The default for the package is to use a thin space
as a group separator between digits. An S column
basically applies \num to every entry, but also aligns
them at the decimal separator. In the case of ourLeporello table, all entries are integers, so they’reright aligned.
If an entry belonging to an S column is braced,
it will be ignored as far as number alignment isconcerned and centered on the total width of the column (options are available for left or right alignment).
This is obviously needed in the header.
With another option we can easily scale down
the figures:
NationNumber

Italy
Germany
FranceTurkey
Spain

640
× 103
232
× 103
100 × 103
91.3 × 103
1.00 × 106

et Mesures (BIPM). This is also part of the ISO
standard mentioned before:\SI{1}{\newton} is defined as\SI{1}{\kilogram\meter\per\second\squared}
will typeset “1 N is defined as 1 kg m s−2 ”. However,
if we prefer slashes instead of negative exponents, we
can add to the preamble\sisetup{per-mode=symbol}
and the same text will now typeset as “1 N is definedas 1 kg m/s2 ”. The mode can also be changed on a
local basis with an optional argument to \SI.
All SI units and prefixes are supported:\SI{5}{\tera\meter} \SI{2}{\pico\farad}yields 5 Tm and 2 pF. One can also print just a unit
with \si: the unit for energy is the J which is thesame as kg m2 s−2 .
Going on with our fictional scientist who’s uncertain where her breakthrough paper will be published,decimal numbers might require the period as separator, or the comma; in scientific notation, there could
be the ×10n part or En might be asked for. How to
do it? Not to mention uncertainty! Let’s take as an
example the rest mass of the electron
9.109 383 701 5(28) × 10−31 kg

This is achieved with the options

9.1093837015(28) × 10−31 kg\sisetup{round-mode=figures,round-precision=3,
scientific-notation=engineering}

9,109 383 701 5(28) × 10−31 kg

9.109 383 701 5(28)E−31 kg

and by changing the column specifier to

The first line has been input with

S[table-format=3.2e1]\SI{9.1093837015(28)E-31}{\kilogram}which directs to reserve space for three digits in
the integer part, two in the mantissa and one in
the exponent. The table body in the input has notchanged in any way.
One might write an entire large chapter of The
LATEX Companion about siunitx. Some time ago,
Joseph Wright took up the job of making a successor
package to SIunit adding some features along theway. For version 2 he had the idea of exploiting expl3
which not only allowed for many more features andfacilities, but made him enter the LATEX team.7 He’s
into chemistry, and tables with numeric data are his
staple food.
The main purpose of the package is of course
typesetting numbers with their SI unit according to
the guidelines of the Bureau International des Poids

and the following lines by adding an option

7 It seems that understanding and propagating expl3 opens
a straight way to the team.

Enrico Gregorio(9.109 383 701 5 ± 0.000 000 002 8) × 10−31 kg
9.109 383 701 5 × 10−31 kg\SI[hoptioni]{9.1093837015(28)E-31}{\kilogram}
The used options are, in order,
output-decimal-marker={,}group-digits=integer
separate-uncertainty
omit-uncertainty
output-exponent-marker=\mathrm{E}and they can be combined to get the desired effectwithout changing the code in the document if thesettings are done with \sisetup in the document
preamble. When inputting numbers, one can use
spaces and either a decimal period or decimal comma.
The first mandatory argument to \SI behaves thesame as the mandatory argument to \num, so I’ll use
the latter:

TUGboat, Volume 41 (2020), No. 1
References\num{12345.678}\num{12345,678}\num{12 345.678}
will print the same
12 345.678

12 345.678

12 345.678

Very few things are hardwired in siunitx: one caninstruct it to ignore something, for instance. Suppose
you have a set of numbers with comma separatorsfor groups: the big number already used might occur in the source file as 7,400,043,022,221. Set(globally or locally) the input-ignore option andwe can remove the comma from the possible decimal
separators:\num[
input-ignore={,},
input-decimal-markers={.}]{7,400,043,022,221}
and you’ll get
7 400 043 022 221
The package is not limited to ‘standard numbers’: italso copes with angles, time and complex numbers.
For instance, we can type\ang{30.24}\ang{30;12;44.375}\num{3-4i}
to get30.24°, 30°12 44.375 , 3 − 4i
000

Oh, dear! An upright ‘i’! Let’s fix it with\sisetup{
output-complex-root=\mathnormal{i}}(one could also tell it to use ‘j‘, of course) and get
3 − 4iPhew! Yes, the package obviously adheres to the
ISO standard, but it’s very customizable.
753

Further reading

Twenty-two years have passed from the seminal paper by Claudio Beccari: we have seen great progressin the field of math typesetting, in particular towards the uniformity that’s necessary in technicaland commercial reports.
There are other packages that can be tried
for the purpose of compliance to the ISO 800002:2009 standard. I would mention isomath by Günter
Milde [7] and also unicode-math by Will Robertson [8]that provided facilities to the purpose; the former
is for legacy pdflatex, the latter for XELATEX andLuaLATEX.

[1] C. Beccari. Typesetting mathematics
for science and technology according toISO 31/XI. TUGboat 18(1), 1997. https://tug.org/TUGboat/tb18-1/tb54becc.pdf[2] J. Dieudonné. Treatise on Analysis.
Vol. III. Academic Press, New York-London,
1972. Translated from the French by I. G.
MacDonald, Pure and Applied Mathematics,
Vol. 10-III.
[3] R. L. Graham, D. E. Knuth, andO. Patashnik. Concrete Mathematics.
Addison-Wesley Publishing Company,
Advanced Book Program, Reading, MA, 1989.
A foundation for computer science.
[4] E. Gregorio. Simboli matematici in TEX e
LATEX. ArsTEXnica 8:7–24, Ottobre 2009.
https://www.guitex.org/home/numero-8[5] M. Guiggiani and L. F. Mori. Consigli
su come non maltrattare le formule
matematiche. ArsTEXnica 5:5–14, Aprile 2008.
https://www.guitex.org/home/numero-5[6] M. Guiggiani and L. F. Mori. Suggestions on
how not to mishandle mathematical formulae.
TUGboat 29(2), 2008. https://tug.org/
TUGboat/tb29-2/tb92guiggiani.pdf[7] G. Milde. isomath — mathematical style forscience and technology, 2012. Version 0.6.1.
https://ctan.org/pkg/isomath[8] W. Robertson. Experimental Unicode
mathematical typesetting: The unicode-mathpackage, 2019. Version 0.8o.
https://ctan.org/pkg/unicode-math[9] W. Rudin. Real and Complex Analysis.
McGraw-Hill Book Co., New York–Toronto,
Ont.–London, 1966.
[10] W. Rudin. Analisi Reale e Complessa.
Bollati Boringhieri, 1974.
[11] C. Tellechea. L’extension pour TEX
et LATEX systeme, 2019. Version 0.32.
https://ctan.org/pkg/systeme[12] J. Wright. siunitx — A comprehensive(SI) units package, 2018. Version 2.7.
https://ctan.org/pkg/siunitx
 Enrico Gregorio
Dipartimento di Informatica,
Università di Verona
enrico dot gregorio at univr dot it

TEX, LATEX and math