--- title: LaTeX date: 2015-06-02 14:40 modified: 2016-03-13 10:51 status: published layout: ../layouts/Post.astro --- I have helped typeset three theses and many shorter documents in LaTeX and I realized that I find myself googling the same things over and over again. Therefore I decided to collect all the problems I have solved so far on this page. At the bottom there is a list of unsolved problems. The reader is invited to give me advice in the comments. I will update this page when I learn new things. This page is meant mostly as a reference for myself or others, for _how_ to solve certain problems, technically. There won't be much discussion of _why_ you should do something a particular way. If you want to know more about that, I suggest you start with [Practical Typography][butterick] and if you're still interested in typography after that, you can move on to [The Elements of Typographic Style][bringhurst] or something. [butterick]: http://practicaltypography.com [bringhurst]: http://www.amazon.de/Elements-Typographic-Style-Version-Anniversary/dp/0881792128/ref=sr_1_1?ie=UTF8&qid=1432924031&sr=8-1&keywords=the+elements+of+typographic+style ## Contents # Standard packages for every document ```latex \usepackage[a4paper, left=4.5cm, right=4.5cm, top=3cm, bottom=4.5cm, marginparwidth=4cm]{geometry} \usepackage[utf8]{inputenc} \usepackage{amsmath,amssymb} \usepackage[hidelinks=true]{hyperref} \usepackage[T1]{fontenc} ``` You probably know what most of these do. The `geometry` settings used here work well for symmetrical layouts. For asymmetrical layouts I like to use 2cm/6cm for `inner`/`outer`. That way I can put [footnotes](#footnotes-as-margin-notes) and [pictures](#margin-figures) in the margins. # Microtype ```latex \usepackage[activate={true,nocompatibility},final=true,kerning=true,spacing=true,tracking=true,shrink=30,stretch=30,factor=0]{microtype} \microtypecontext{spacing=french} ``` Apart from the standard packages above, the `microtype` package is the single most important package in existence and should be included in every document. It does a number of things: - Glyph reshaping. Characters are stretched or shrunk by up to 3% (adjustable with `shrink` and `stretch`) to improve justification. This will save you many overfull hboxes and even get rid of a lot of hyphenation without producing overlarge spaces. - `kerning` and `spacing` probably fixes some kerning and spacing issues. `tracking` adds some letter spacing for small caps.[^Butterick] - `nocompatibility` means you get the best possible result instead of `microtype` trying to keep the page breaks and such the same as without the package. - `factor` controls how much punctuation protrudes past the end of the line. Some people, for example, like having hyphens at the ends of lines sticking out into the margin. Personally, I don’t like that. You get 100% protrusion with `factor=1000`. - `final=true` means `microtype` is activated even when you use the `draft` option in the `documentclass` declaration. This doesn’t have any effect on the final document. - `spacing=french` is the same as calling `\frenchspacing` in the document body and prevents spaces between sentences from stretching wider than a normal word space. You might like that, but french spacing is the standard for most printed material nowadays. # Fonts I don't have a huge problem with Computer Modern, but (1) it is overused, and (2) since it's the default, most typographic sins are committed with Computer Modern, so I sometimes get a bad feeling about it (like with Times). These are some acceptable fonts: ## Palatino ```latex \usepackage[osf,sc]{mathpazo} ``` Palatino is like the Times New Roman of pretty fonts. It's like everyone who's unsatisfied with Times goes through their system fonts and says, "oh, that looks fancy!" and chooses Palatino. This means it comes close to being overused, but it still looks good enough that you can use it without feeling bad. Also, the `mathpazo` package offers real small caps (`sc`), oldstyle numerals (`osf`), and most of the mathematical symbols you will ever need. It also works well with Euler math if you're into that kind of thing. ```latex \usepackage{euler} ``` ## The Johannes Kepler Project ```latex \usepackage[oldstylenums]{kpfonts} ``` I've not used this font yet but, apart from the capital T, I like the look of it. Like Palatino, Kepler offers real oldstyle figures, real small caps, and extensive math support. There is also a sans serif version of Kepler that you might want to use in combination with the serif version, but I haven't looked at that, so it might suck. If you're inclined to save ink, Kepler also has a `light` option.[^kp-light] ## A note on numerals In normal text, you want to use oldstyle figures[^numerals] (lowercase numbers). You only want to use lining figures (uppercase numbers) in combination with all caps, in mathematical expressions, or in tables. With the settings I've described above, Palatino and Kepler will automatically switch to lining figures in math mode. If you want to set all the numbers in a block as lining figures, you can place ```latex \fontfamily{pplx}\selectfont ``` for Palatino, and ```latex \fontfamily{jkpx}\selectfont ``` for Kepler at the beginning of the block. # Spacing ```latex \usepackage{setspace} \setstretch{1.1} \setlength{\parskip}{0pt} \setlength{\parindent}{1.4em} ``` The default line spacing (`\setstretch`) is usually too narrow. For most texts, a setting of `1.1` looks good, for very math-heavy or German texts I go up to `1.14` to avoid collisions between ascenders, descenders, accented mathematical symbols, etc. I prefer indented paragraphs to vertically spaced paragraphs. If you like vertical space between your paragraphs, set `\parindent` to 0; if you like indented paragraphs, set `\parskip` to 0. Otherwise LaTeX may add spacing between paragraphs, which will look hideous if the paragraphs are indented. # Colors To define colors: ```latex \usepackage{color} \definecolor{color-name}{gray}{0.8} \definecolor{other-color}{rgb}{0.8, 0.9, 1} ``` To use colors: ```latex \color{color-name} ``` # Tables ```latex \usepackage{booktabs,suinitx} \begin{table}[htb]\fontfamily{pplx}\selectfont \begin{center} \begin{tabular}{lrcS[table-format=1.1]} \toprule% left & right & centered & \multicolumn{1}{c}{aligned numbers}\\\midrule{} 1 & 2 & 3 & 4.5 \\ \bottomrule{} \end{tabular} \caption{Description} \label{tab:label} \end{center} \end{table} ``` The `S` alignment option aligns numbers by their decimal point. Because the column title isn't a number, it needs to be wrapped inside the weird `\multicolumn` command. The `[table-format=x.y]` aligns the column in a way that numbers with `x` digits to the left and `y` digits to the right of the decimal point are centered. You can omit this option if everything looks fine, but it's useful as soon as you have different numbers of digits in each row. If you use `S`, the numbers will be set in math-mode, so they will automatically be lining figures. If you use `l`, `r`, or `c`, you will have to declare the `\fontfamily` at the top of the table to get them to look right. ## Colored cells Include the package ```latex \usepackage{colortbl} ``` and call ```latex \cellcolor{color-name} ``` inside your table-cell. The cell coloring doesn't go all the way to horizontal rules, making the coloring discontinuous. That looks weird when you want to have entire columns in one color. I haven't figured out how to prevent that. ![Table with colored cells.](https://i.imgur.com/Q8BWhBS.png) # Prettier unordered lists ```latex \newcommand{\sbt}{\,\begin{picture}(-1,1)(-1,-3)\circle*{2.2}\end{picture}\ } \renewcommand{\labelitemi}{\sbt} \renewcommand{\labelitemii}{\sbt} ``` The bullet character (•) is too large. To get better looking bulleted lists, this snipped works wonders. You can manipulate the size of the circle by changing the `2.2` above to something else. If you need more than two levels in your lists, you can duplicate the last line and change `\labelitemii` to `\labelitemiii`. # Prettier ordered lists ```latex \usepackage{enumerate} \begin{enumerate}[1] \item Item One \item Item Two \end{enumerate} ``` Make numbered lists less cluttered. ![Better lists](https://i.imgur.com/Fjjl4ei.png) # Headers and footers If you're using the `book` document class, _never ever_ use the default headers. I don't know whose idea it was to make the headers _ITALIC ALL CAPS_, but trust me, it was a terrible idea. This setting was surprisingly difficult to change, too. ```latex \newcommand{\spacedlowsmallcaps}[1]{\lowercase{\textsc{#1}}} \usepackage[automark]{scrpage2} \clearscrheadings \renewcommand{\chaptermark}[1]{\markboth{\spacedlowsmallcaps{#1}}{\spacedlowsmallcaps{#1}}} \renewcommand{\sectionmark}[1]{\markright{\thesection\enspace\spacedlowsmallcaps{#1}}} \lehead{\mbox{\llap{\small\thepage\kern2em}\hfil{\headmark}}} \rohead{\mbox{\hfil{\headmark}\rlap{\small\kern2em\thepage}}} \renewcommand{\headfont}{\small} ``` I don't even want to look at those settings. ![Example headers](https://i.imgur.com/cmAyiwd.png) You can take this as inspiration and go from there. # Chapter and section headings + spacing ```latex \usepackage{titlesec} \newfont{\chapterNumber}{eurb10 scaled 7000} \titleformat{\chapter}[display]% {\relax}{\mbox{}\marginpar{\vspace*{-\baselineskip}\color{chapternumbergray}\chapterNumber\thechapter}}{0pt}% {\LARGE\itshape}[\normalsize\vspace*{.8\baselineskip}\titlerule]% \titlespacing*{\chapter}{0pt}{0cm}{1cm} \titleformat{\section}{\Large}{\makebox[0cm][r]{\thesection\hspace{1em}}}{0em}{\scshape\lowercase} \titlespacing*{\section}{0pt}{\baselineskip}{\baselineskip} \titleformat{\subsection}{\large}{\thesubsection}{.6em}{\itshape} \titlespacing*{\subsection}{0pt}{\baselineskip}{\baselineskip} \titleformat{\subsubsection}{\bfseries}{}{}{} \titlespacing*{\subsubsection}{0pt}{\baselineskip}{\baselineskip} ``` ![Headings](https://i.imgur.com/iaELHja.png) These settings are strongly inspired by Robert Bringhurst's [The Elements of Typographic Style][bringhurst]. The chapter numbers are set in the Euler font. # Custom table of contents ```latex \usepackage{tocloft} \usepackage{textcase} \setcounter{tocdepth}{2} ``` Chapters: ```latex \renewcommand{\cftchappresnum}{\bfseries} \renewcommand{\cftchapfont}{\normalfont} \renewcommand{\cftchappagefont}{\color{pagenumbergray}\normalfont} \renewcommand{\cftchapleader}{\hspace{1.5em}} \renewcommand{\cftchapafterpnum}{\cftparfillskip} ``` Sections: ```latex \renewcommand{\cftsecpresnum}{\scshape} \renewcommand{\cftsecfont}{\normalfont} \renewcommand{\cftsecpagefont}{\color{pagenumbergray}\normalfont} \renewcommand{\cftsecleader}{\hspace{1.5em}} \renewcommand{\cftsecafterpnum}{\cftparfillskip} ``` Subsections: ```latex \renewcommand{\cftsubsecpresnum}{\scshape} \renewcommand{\cftsubsecfont}{\normalfont} \renewcommand{\cftsubsecpagefont}{\color{pagenumbergray}\normalfont} \renewcommand{\cftsubsecleader}{\hspace{1.5em}} \renewcommand{\cftsubsecafterpnum}{\cftparfillskip} ``` This is in part influenced by Bringhurst and in part by common sense. Most tables of content are typeset terribly. # Title page An example for a title page. The contents of this will depend very strongly on the specific document you're making. ```latex \begin{titlepage} \begin{center} {\LARGE University Name}\\ \begin{figure}[h] \hbox{}\hfill \begin{minipage}[t]{10cm} \begin{center} \includegraphics[width=5cm]{university-logo} \end{center} \end{minipage} \hfill\hbox{} \end{figure} {\large Department or something\\[2cm]} {\huge Bachelor's Thesis\\[1cm]} {\Large\bf Title\\[1.0cm]} {\small Author:}\\[0.2cm] {\large Author}\\[0.2cm] {\small date}\\[0.8cm] {\small Advisor:}\\[0.2cm] {\large Advisor name}\\[0.2cm] Advisor's employer\\[2.2cm] {\small Address} \end{center} \end{titlepage} ``` # Figures ## Regular floating figures ```latex \begin{figure}[tbh] \centering \includegraphics[width=8cm]{bunnies.jpg} \caption{A normal figure.} \label{fig:normal} \end{figure} ``` Sometimes you want to put a `p` in the position options, too. ## Margin figures ```latex \marginpar{ % \includegraphics[width=\marginparwidth]{picture}% \captionof{figure}{A margin figure.}% \label{fig:marginfig}% } ``` For best results, use [`\raggedright` or `\RaggedRight`](#footnotes-as-margin-notes). # Footnotes as margin notes ```latex \usepackage{ragged2e} \newcounter{mnote} \renewcommand{\footnote}[1]{ % \refstepcounter{mnote}% \mbox{\textsuperscript{\themnote}}% \marginpar{\footnotesize\RaggedRight\mbox{\themnote}\hspace{5pt}#1}% } ``` You can call these with `\footnote`. If you need to move the content of the footnote up along the margin, use ```latex \newcommand{\fnhere}[1]{\refstepcounter{mnote}\marginpar{\footnotesize\RaggedRight\mbox{\themnote}\hspace{5pt}#1}} \newcommand{\fnref}{\mbox{\textsuperscript{\themnote}}} ``` Then you can call `\fnhere{Footnote content}` where you want the note to appear in the margin and `\fnref{}` where you want the reference to appear in the text. This is only for moving footnotes _up_. They should move _down_ automatically, if there are other `\marginpar`s in the way. `\raggedright` makes the text left-aligned, which looks better because margins are usually too narrow for proper justified text. `\RaggedRight` requires the `ragged2e` package and will re-enable hyphenation for the left-aligned text. # Some symbols Some symbols I sometimes forget. - `\textperiodcentered` becomes the mid-dot (·). You should use this more. # Kerning ```latex a\kern+1ptb ``` This adds 1pt of separation between the letters a and b. When I have the time, I use this extensively for adding space to the insides of paretheses since they're set too tight in most fonts. Also works in math mode. # Colored boxes I rarely use these because I always run into problems. But it can be kinda pretty and you can probably fix the issues if your document isn't too complex. ```latex \definecolor{boxblue}{rgb}{0.8, 0.9, 1} \usepackage[framemethod=tikz]{mdframed} \newmdenv[innerlinewidth=0.5pt,roundcorner=2pt,backgroundcolor=boxblue, linecolor=boxblue,innerleftmargin=6mm,innerrightmargin=6mm,innertopmargin=6pt,innerbottommargin=6pt,skipabove=1ex,skipbelow=1ex]{mybox} ``` You use this with ```latex \begin{mybox} Content \end{mybox} ``` ![Colored boxes](https://i.imgur.com/oVrY7eB.png) # Prettier ellipsis ```latex \newcommand{\dotdot}{.\hspace{.6pt}.\hspace{.6pt}.} ``` The normal `\ldots{}` command creates too much space between the dots and, even with french spacing turned on, the amounts of space to the left and right of the ellipsis aren't the same, so it looks uneven. You may need to adjust the amount of `\hspace`, depending on the font. Comparison: ![Comparison between `\ldots` and `\dotdot`](https://i.imgur.com/GDuFDyF.png) # Only numbering certain lines of an `align` environment ```latex \begin{align} 1 + 2 &= a\nonumber\\ 3 + 4 &= b \cdot e^{2\tau}\nonumber\\ 6 + 1 &= c \end{align} ``` ![Only the third line has a number](https://i.imgur.com/Gyxnnvw.png) # What I haven't figured out yet - Outdented lists, such that the bullet symbol or number is placed in the margin. Those are pretty. - Global kerning pairs without using LuaLaTeX. Alternatively: Get `microtype` to run in LuaLaTeX. Kerning parentheses manually takes a lot of time and search-and-replace is messy. - Figures that take up the whole width of the text and have their description as a `\marginpar`. - Figures that take up a fraction (e.g. half) of the text-width and have the description in the remaining space next to them. - Full width figures that are as wide as the text plus the width of `\marginpar`s and have their description below. [^Butterick]: From [Practical Typography](http://practicaltypography.com/letterspacing.html): > Lowercase letters don’t ordinarily need letterspacing. Nor do capital letters when they appear at the beginning of a word or sentence, because they’re designed to fit correctly next to lowercase letters. But when you use capital letters together, that spacing looks too tight. > > That’s why you always add 5--12% extra letterspacing to text in all caps or small caps, particularly at small sizes. [^kp-light]: From the [documentation](ftp://ftp.fu-berlin.de/tex/CTAN/fonts/kpfonts/doc/kpfonts.pdf): > Save up your toner and the environment, use the "light" option, it’s 20% toner less! > The metrics are the same. The display is not very good, but the print is fine if you like light fonts. [^numerals]: I never know which word to use. "Numerals"? "Figures"? "Numbers"? And then I just end up using them all interchangeably and it's terrible.