LATEX Weekend

A Fachschaft WIAI workshop. Presented by Alice, Christian, Clara, Evelyn, Fabian, Florian, Jochen, Katharina, Kilian, Paul, and Sandra.

Procedure of this workshop

Goal: You are going to build your own little
LaTeX manual based on our LaTeX Script.

  • learning by doing
  • understanding how LaTeX works
  • details can be looked up later

Outline:

  1. What is LaTeX?
  2. Basic LaTeX documents
  3. More complex projects
  4. Lots of features
  5. Reference management
  6. Outlook

1 . What is LATEX?

Origin

  • Donald Knuth, 1977–1986: typesetting system TeXτεχ → /tɛç, tɛx, tɛk/ for The Art of Computer Programming
  • Leslie Lamport, from 1980s: software package LaTeX made TeX easier to use
Donald Knuth
Leslie Lamport

5 Reasons for LaTeX

  1. Besides Word, LaTeX is one of the two dominant typesetting systems in the academic world.
  2. Mathematical formulas feel most at home in LaTeX. This is why the LaTeX formula notation has been integrated into numerous other tools (e. g. OneNote, Word, Wikipedia, …).
  3. There are countless packages for the most diverse areas of application.
  4. LaTeX was developed to produce aesthetically pleasing typesetting — and you can see that in the texts it produces.
  5. Complex documents typeset in LaTeX facilitate collaboration enormously (e. g. through versioning, proper document structuring, templates, reliable undo, …).

LaTeX’ Shortcomings

  • Typesetting text can be cumbersome, especially for short documents.
  • Layout adjustments are only possible within certain limits.

The “LaTeX vs. Word” debate is very old. If you are interested in tracing it, we can recommend the following article as a starting point:

Moorhead, A.V. Is LaTeX use correlated with the number of equations in a manuscript? Scientometrics 126, 8259–8273 (2021).

(TL;DR: LaTeX users make more errors, they need more time except when it comes to formulas, but they are happier with their tool.)

WYSIWhat?

What You See Is What You Get

  • Formatting with immediate visual feedback

What You See Is What You Mean

  • Separation of content and structure
  • Formatting only visible afterwards

Image source: xkcd

How to get the final document

What do we need?

Compiler

takes the source code and creates a PDF document ready for publication

MiKTeX (Windows), MacTeX (macOS)
TeX Live (Linux, preferably texlive-full)

On Windows, please open the MikTEX Console once and search for updates.

Editor

writing our source code including all the commands that structure the text semantically

TeXstudio (recommended), VS Codium (for advanced users, instructions on Github)

Compile the script for the first time

  • Download the project archive from the VC.
  • Unzip the archive.
  • Open the file install-verification/main.tex in TEXstudio.
  • Compile the file by pressing
  • Have a look at the new files that will be generated by the compilation.

Windows: In order to enable file endings, click the view tab in the file explorer, and select file name extensions. This helps differentiating the different main files.

Micro- and Macrotypography

Text typesetting is particularly good when it is not conspicuous. Or to put it another way: Good typesetting makes for effortless reading. This website impressively demonstrates the role played by fonts and font sizes, line spacing and many other factors:

https://legibility.info/legible-readable

The best thing about it: LaTeX does most of this manual work for us.

2 . Basic documents

Commands

General structure of a command:

\<command>[<optional_parameters>]{<obligatory_parameters>}

A few examples:

\newpage % inserts a new page
\textbf{bold text} % formats the text bold
\documentclass[a4paper,12pt,landscape]{article} % configures the document class
\frac{1}{4} % inserts a mathematical fraction

Backslash

Assuming a German keyboard layout, you get the backslash by pressing

AltGr + ß (Windows/Linux)

Alt + Shift + 7 (MacOS)

Preamble & document environment

👁 Every LaTeX document is composed of

  • a preamble: global settings (document class, encoding, language, page format, additional packages, …) and
  • a document environment: content of the document.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{babel}

\begin{document}
Hello world!
\end{document}

Document class

\documentclass[<parameter>]{<document_class>}

For example:

\documentclass[10pt,a5paper,landscape]{article}

Encoding

\usepackage[utf8]{inputenc}
\usepackage[t1]{fontenc}
  • The character encoding determines which characters are available.
  • ASCII contains no special characters like German umlauts.
  • UTF-8 is a universal encoding.

Language

\usepackage[ngerman]{babel}
  • The package babel provides language-specific information (e. g., hyphenation, special characters, font changes, translated labels like ‘chapter,’ ‘table of contents’ or ‘figure’).
  • ngerman is the German new spelling.

Continuous Text

Continous text can be written directly ↲
in the source code. ↲
Simple line breaks ↲
are ignored, ↲
just as     multiple space characters. ↲
↲
An empty line creates a new paragraph ↲
which has an indentation by default. ↲
Manual line breaks can be forced ↲
using two backslashes, but this use ↲
is strongly discouraged \\ ↲
within continuous text.

Comments

After a percent sign, the rest of the line is ignored by the compiler. It is called a comment and does not appear in the resulting document.

% profile start
Name: Donald Knuth \\
Date of birth: \\ % TODO: insert
Place of birth: Milwaukee, Wisconsin
% profile end

Shortcuts: Ctrl + T and Ctrl + U

Reserved characters

Some characters do things in LaTeX:

# $ % ^ & _ { } ~ \

50% is one half.

Solution: prefix with ‘\’:

50\% is one half.

Does not work for ‘\\’, use \textbackslash instead. Also: Consider using a thin space between numbers and units (50\,\%).

Sections and chapters

Texts are structured by beeing subdivided in sections and chapters. Always available:

\section{Level 1}
\subsection{Level 2}
\subsubsection{Level 3}
\paragraph{Level 4}
\subparagraph{Level 5}

Additionally, for some document classes:

\chapter{Chapter}
\part{Part}

Title page

\title{The World of Truffles}
\author{Fooboar Rüssel \and Fachschaft WIAI}
\date{\today}
\begin{document}
\maketitle
\end{document}
  • The values for the entries are stored in the preamble.
  • \maketitle typesets the title page within the document environment.
  • The exact appearance depends on the document class.
  • Multiple authors can be joined with \and.
  • If no date is given, the current date will be used. A different date can be defined with \date{}.

Front matter

\documentclass{article}
\usepackage{babel}
\title{The World of Truffles}
\author{Fooboar Rüssel 
\and Fachschaft WIAI}
\date{\today}

\begin{document}
    \maketitle
    \section{Truffle hunt}
    \subsection{Hunt with a pig}
    \subsection{Hunt without a pig}
    Why would you do that?
    \section{Truffle recipes}
    My favorite recipe
\end{document}

Registers

\tableofcontents
\listoffigures
\listoftables
  • automatic numbering
  • elements with an asterisk (*) are hidden from the register: e. g. \section*{}.
  • generally requires two rounds of compilation

Table of contents

\documentclass{article}
\usepackage{babel}
\begin{document}
    \tableofcontents
    \section{Truffle hunt}
    The first section.
    \subsection{Hunt with a pig}
    A subsection.
    \subsection{Hunt without a pig}
    Another subsection.
    \subsubsection[But why?]{Why would 
    you do that?}
    Sub-subsection.
    \section{Truffle recipes}
    My favorite recipe
\end{document}

Structure your document and text

Close all open tabs from previous tasks.

  • Open the file document-structure.tex. It is located in the directory exercises/basic-document-structure.
  • Wrap the entire text in a document environment and insert the following preamble.
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
  • As you may already have noticed, paragraphs are marked as ‘\\’. Use real paragraphs instead.
  • Time to structure our document! Use LaTex commands to declare all headings (\section, \subsubsection, etc.).
  • Add a table of contents to your document.

Document classes

  • There are also other document classes than article.
  • Based on the document class, the layout of the generated pdf file changes.
  • Normally spelled classes adhere to American English layout norms.
  • scr document classes usually adhere to European layout norms.

Following document classes are available:

  • scrartcl, article for short documents
  • scrreprt, report for longer documents
  • scrbook, book for books
  • beamer for presentations

Languages

A document can use multiple languages at once:

\usepackage[ngerman, swedish, ukrainian, greek, english]{babel}

To switch languages:

\selectlanguage{<language a>}
\selectlanguage{<language b>}

Embedded Text in another language:

\selectlanguage{<language a>}
\foreignlanguage{<language b>}{Text of language B in a text of language A}

Languages — an example

\today
\selectlanguage{ngerman}
\today
\selectlanguage{swedish}
\today
\selectlanguage{ukrainian}
\today
\selectlanguage{greek}
\today
\selectlanguage{english}
\today

Headlines and the table of contents

With an asterisk, there is no numbering and no entry in the table of contents:

\section*{No entry in table of contents}

You can also provide an alternative title for the table of contents:

\section[Entry in table of contents]
{Actual chapter heading}

Headers and footers

The fancyhdr package helps us with that.

% activate in general
\pagestyle{fancy}     

% apply to the first page as well
\thispagestyle{fancy} 

% reset values
\fancyhead{} % and/or \fancyfoot{}
\fancyhead[L]{Left header}
\fancyfoot[C]{Center footer}
\fancyfoot[R]{\thepage}

A comprehensive tutorial can be found on Overleaf.

Make it fit your needs

  • Add a title to the document.
  • Make today’s date appear in a language of your choice.
  • Hide one section title in the table of contents.
  • Add a short title to a different section title.
  • Split the text in two columns (keyword: twocolumn).
  • Add a header with the title on the right and a footer with the page number on the left.
  • Try out what changes when you change the document class.
  • Research the possibilities of traditional and modern beamer presentation templates.

3 . Complex projects

Goal

Create a bigger LaTeX project and …

  • prevent LaTeX documents from growing monstrously 👹
  • keep the overview over the project structure

Main file 👑

  • contains basic structure
  • includes separate sections with
    \input{path/to/file}
\documentclass{article}
\usepackage{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\title{A Title}
\begin{document}
    \maketitle
    \tableofcontents
    \input{section1.tex}
    \input{section2.tex}
\end{document}

File with a section

  • contains no preamble
  • contains no \begin{document} or \end{document}
\section{This is section 1}
A paragraph about the content 
of section 1.

% …
\section{This is section 2}
A paragraph about the content 
of section 2.

% …

Compiling the project

  • Only the main file has to be compiled to get the complete PDF document.
  • Error messages include a reference to the corresponding subfile.
  • Subfiles cannot be compiled on their own as they don’t have a preamble.

A structured project

Close all open tabs from previous tasks.

You will find a file named main.tex in the folder exercises/project-structure.

  • Put the sections of the file into separate files, named section1.tex and section2.tex.
  • Include them using the \input command.
  • Move the preamble to its own file in a similar fashion.
  • Finally, have a look at the general project archive, starting from main-exercises.tex (in the root folder of the project archive). How do we include the different sections here?

Embedding PDF documents

The pdfpages package allows for embedding entire PDF documents.

\includepdf[pages={<from>-<to>}]{<file>}

Further options make multiple pages appear in tiles and change the orientation to landscape, among other things. See the package documentation for a complete list.

Macros

It may be helpful to specify custom macros for often-used code.

\newcommand{\<name>}[<parameter_count>][<default>]{<content>}

In the script, we used these macros for margins and acronyms (see commands.tex for more examples):

\newcommand{\widefiguremargin}{-.22\textwidth}
\newcommand{\acro}[1]{\textsc{\lowercase{#1}}}

It is also possible to customize existing commands. \(\LaTeX\) even allows you to use programming patterns like variables, conditionals, and loops. To learn more, have a look at this WikiBook chapter.

Specifying file paths 👣

  • important for \input{}, but later also for other media types
  • file and folder structure = tree structure 🌳
  • with \input{}, you can specify the path relative to the main file

In LaTeX, you have to use UNIX-style paths. They are separated by a forward slash: path/to/file. We will use those from here on.

Specifying file paths 👣

main-exercises.texpraeamble.tex

./praeamble.tex

A single dot ‘. represents the current folder (in this case: latex-script). It is optional, you could also write praeamble.tex here.

Specifying file paths 👣

main-exercises.texbasic-document-structure.tex (in a subfolder)

./content/basic-document-structure.tex

Specifying file paths 👣

basic-functionality.texgraphics.raw.tex

(basic-functionality.tex is imported into main-exercises.tex)

./exercises/graphics/graphics.raw.tex

Paths are always relative to the root document that imports other files as fragments.

Note

  • From now on, we will compile the file main-exercises.tex in the project root.
  • To do so, right click on the file in TeXstudio and choose “Select as explicit root document” from the dropdown.
  • Next, compile as usual.

4 . Special characters

Spaces

  • Use thin spaces (\,) and non-breaking spaces (~), where appropriate.
Thin spaces are used in abbreviations
and before units, e.\,g., 10\,s.
Normal-width non-breaking spaces can help
keep honorary titles and names on one
line: Dr.~Fooboar.
  • Use french spacing (\frenchspacing) to avoid giant gaps after full stops.

Hyphens and dashes

Name Use Code
- Hyphen compound-forming hyphen -
En dash (Halbgeviert­strich) a dash – or a range: 12 – 2 p.m. --
Em dash (Geviertstrich) a dash — mostly in American English ---

Quotes

The csquotes package provides, amongst others, the command \enquote.

\enquote{A \enquote{nested}
quote.}

When included with autostyle=true, foreign-language quotes use the according quotation marks:

\foreignquote{ngerman}{Ein deutsches
Zitat.}

Special characters & symbols

Detexify to the rescue! ⛑️

Insert special characters

From now on, compile the file main-exercises.tex to see your changes appear in the exercise script (in this task, see exercise 5).

  • Replace the spaces in exercises/special-characters.tex within the abbreviations (“e. g.”, “i. a.”) by thin spaces.
  • Replace the hyphens separating the opening hours by en dashes (--), optionally surrounded by thin spaces.
  • Add quotation marks around the words Studi-Ticket and Studi-Karte using the \enquote command.

English and French spacing

In English, LaTeX uses the old-fashioned English spacing, i. e., double sentence spacing.

If you want to be more modern, you can use \frenchspacing above your first paragraph. \nonfrenchspacing goes back to default.

If you actually use English spacing, LaTeX will still try and put normal word spacing after abbreviations. However, you should check the results and intervene where needed by

  • forcing normal spaces: .\␣
  • manually ending sentences: \@.␣

Hyphenation

Most of the time, LaTeX hyphenates words correctly if the correct language is configured. Sometimes, manual intervention is required.

Exclusive hyphenation \-
Additional hyphenation "-
Hyphen (suppressing other hyphenation) -
Hyphen (allowing other hyphenation) "=
Possible separation without hyphen ""
Non-breaking hyphen "~

Some of the codes only work when you use the babel package.

Manual quotation

Language Command Result
English (B. E.) `…' ‘ … ’
 2nd Level ``…'' “ … ”
English (A. E.) ``…'' “ … ”
 2nd Level `…' ‘ … ’
German \glqq … \grqq „ … “
 2nd Level \glq … \grq ‚ … ’
German altern. \frqq … \flqq » … «
 2nd Level \frq … \flq › … ‹

Other rules my apply for other languages (mostly: the same characters, but combined differently).

Diacritics

Letters with diacritics can either by typed directly on the keyboard or via escape codes:

\`{o} ò   \c{c} ç   \d{u}
\'{o} ó \k{a} ą \r{a} å
\^{o} ô \l{} ł \u{o} ŏ
\"{o} ö \={o} ō \v{s} š
\H{o} ő \b{o} o \t{oo} o͡o
\~{o} õ \.{o} ȯ \o ø

Special characters

Special characters can also be typed directly or created via escape codes and commands:

¿ ?` ¡ !`
^ \textasciicircum ~ \textasciitilde
\textasteriskcentered \ \textbackslash
| \textbar \textbullet
\textcopyright \textdagger
\textdaggerdbl \textellipsis
< \textless > \textgreater
\textperthousand § \textsection

… and pretty much anything else.

5 . Text Markup

Emphases

  • semantical emphasis with \emph{}
  • optical highlighting options:
Name Befehl
Bold (bold face) \textbf{important}
Italics (italics) \textit{important}
Small caps \textsc{important}
non-proportional (teletype) \texttt{important}
underlined \underline{important}

Better Call LaTeX!

Some well-meaning advice

You want the entire document to look consistent?

Trust LaTeX’s defaults (font sizes of title, paragraphs, footnotes, etc.)!

This conversely means: Avoid fiddling around with font sizes manually.

URLs

The hyperref package provides an \url{} command that reproduces URLs

  • letter by letter
  • using line breaks without hyphens
  • using a font with well-distinguishable characters
  • as a clickable link in the PDF.
\url{https://www.latex-project.org/}

With \href{}{}, the URL is hidden in an interactive link.

\href{https://latex-project.org/news/}{blog}

Emphasising text

  • Emphasise the words Recursion and recursive in exercises/text-markup/markup.tex using \emph{…}.
  • Make the URL in the text clickable.
  • Find a proper way to display the whole paragraph as a quote. Have a look at the csquotes package.
  • Of course, you can also experiment with the other text markup possibilities. However, remove them afterwards if you want to have a clean document.

Font size

Preset font sizes

{\<fontsize> some text}

Font sizes relative to normalsize:

{\tiny         If}
{\footnotesize you}
{\small        can}
{\normalsize   read}
{\large        this,}
{\Large        you}
{\LARGE        don’t}
{\huge         need}
{\Huge         glasses.}

Ragged alignment

By default, LaTeX sets text in full justification, but it is possible to activate ragged alignment.

\raggedright … \raggedleft …
\centering …

Alternatively, we can use dedicated environments:

\begin{flushleft}  Text \end{flushleft}
\begin{flushright} Text \end{flushright}
\begin{center}     Text \end{center}

Proper ragged alignment is even more difficult than good justification, so better avoid it.

Indentation and spacing

  • paragraphs are usually indicated by first-line indentation (\parindent)
  • we can decide to use paragraph spacing (\parskip) instead (!)
  • both parameters are customisable:
\setlength{\parindent}{0pt}
\setlength{\parskip}{1em
    plus  .5em % permitted stretch
    minus .5em % permitted compression
}
  • \noindent allows us to disable first-line indentation for a given paragraph

6 . Enumerations

Unordered lists 📜

\begin{itemize}
    \item lasagna noodles
    \item crushed tomatoes, % …
    \item oregano, basil, % …
    \item mozzarella cheese
    \item flour
    \item milk
\end{itemize}

We mark each bullet point with \item. This pattern is the same for all kinds of enumerations.

Ordered and definition lists

\begin{enumerate}
  \item cook onions over medium % …
  \item add crushed tomatoes, carrots % …
  \item add herbs and spices % …
  % \item …
\end{enumerate}
\begin{description}
  \item [Béchamel sauce] Béchamel % …
  \item [Lasagne] Lasagne (singular % …
\end{description}

Nested lists

\begin{itemize}
  % …
  \item vegetables \begin{itemize}
    \item crushed tomatoes
    \item carrots
  \end{itemize}
  \item herbs \begin{enumerate}
    \item oregano
    \item basil
  \end{enumerate}
  % …
\end{itemize}

Adding enumerations

  • Turn the recipe in lists.tex into an unordered list consisting of the elements Ingredients and Instructions. You can find the file in the directory exercises/lists. Use the itemize command.
  • Within this list, create an unordered list for the ingredients and an ordered list for the instructions.

Compact lists

The package paralist offers enumerations with less line spacing.

\section{Ingredients}
\begin{compactitem}
  % \item …
\end{compactitem}
\section{Preparation}
\begin{compactenum}
  % \item …
\end{compactenum}
\section{Glossary}
\begin{compactdesc}
  % \item …
\end{compactdesc}

In-line enumerations

Another feature provided by paralist enables us to integrate enumerations into paragraphs.

The following herbs are % …
\begin{inparaitem}
    \item lovage
    \item parsley
    \item chives
\end{inparaitem}

Of course, there is an accompanying list type called inparaenum for ordered lists.

List styles

The list style type can be set using the optional parameter label. To accomplish this, we need to include the package enumitem first (but after all other list-related packages).

% Roman numerals
\begin{enumerate}[label=\roman*]
% …
% Arabic numerals
\begin{enumerate}[label=\arabic*]
% …
% Alphabetical
\begin{enumerate}[label=\alph*]
% …

Special enumerations

  • Try using Roman numerals in the ordered list.
  • Make the ordered list start at 7 (keyword: \setcounter).
  • Reduce the white space between the items in the unordered list.

7 . Typesetting mathematics

Formula environments 🧮

$2 \sqrt{\frac{\pi^2}{3} \cdot c_2}$

Mathematical formulas are only accepted in the so-called math mode. In-line formulas must therefor be guarded by two dollar signs. We can also use the equation block environment:

\begin{equation}
  2 \sqrt{\frac{\pi^2}{3} \cdot c_2}
\end{equation}

Packages: amsmath, amsthm, amssymb, mathtools

Examples

source code result
\sum_{i=1}^{n}x^2 \(\sum_{i=1}^{n} x^2\)
12 \leq 4 x^2 + 13 \(12 \leq 4 x^2 + 13\)
{n \choose k} \({n \choose k}\)

Aligning a group of equations

The align environment permits us to align equations at certain positions like the ‘ = ’ character.

\begin{align}
  13 \cdot (4a - 3)^2 &= 13 … \\
      &= 208a^2 - 312a + 117
\end{align}
  • The equations will be aligned with respect to the ampersands (‘&’).
  • We can mark a new line using ‘\\’.
  • align and equation will not be numbered if we add an asterisk after their names (e. g. \begin{align*} and \end{align*}).

Typesetting mathematics

Code up the following formulas in the file exercises/maths/math-formulas.tex.

Meaning Result
Gravitational acceleration \(9.81\,\frac{m}{s^2}\)
One formula to solve quadratic equations \(x_{1,2} = - \frac{p}{2} \pm \sqrt{\left(\frac{p}{2}\right)^2 - q}\)
The other one \(x_{1,2} = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}\)
Catalan numbers \(C_n = \frac{1}{n+1} {2n \choose n} = \frac{(2n)!}{(n+1)!n!}\)

Typesetting mathematics

Meaning Result
Definition of factorial \(n! = \prod_{i=1}^{n} i\)
Set of all odd natural numbers \(\{ x \mid x \in \mathbb{N}, \text{odd}(x) \}\)
Elimination \(\neg\exists x\) \(\neg\exists x . p(x) \Leftrightarrow \forall x . \neg p(x)\)

Find further examples on the Chair of Algorithms and Complexity Theory’s LaTeX exercise page.

More examples

source code result
(x), [x], \lbrace x \rbrace, \lvert x \rvert \((x), [x], \lbrace x\rbrace, \lvert x\rvert\)
\exists, \forall, \in,
\notin, \infty
\(\exists,\forall,\in,\notin,\infty\)
\alpha, \beta, \Gamma,
\Delta, \varepsilon, \pi
\(\alpha, \beta, \Gamma, \Delta, \varepsilon, \pi\)
\rightarrow, \leftarrow, \Rightarrow, \Leftarrow, \Leftrightarrow \(\rightarrow, \leftarrow, \Rightarrow, \Leftarrow, \Leftrightarrow\)
(A \cup B) \cap C \((A \cup B) \cap C\)
(A \lor B) \land C \((A \lor B) \land C\)
(A \cdot B) \times C \((A \cdot B) \times C\)

Height-adapting braces

source code result
\left( \frac{1}{2} \right) \(\left( \frac{1}{2} \right)\)
\left[ \frac{1}{2} \right] \(\left[ \frac{1}{2} \right]\)
\left\lbrace \frac{1}{2} \right\rbrace \(\left\lbrace \frac{1}{2} \right\rbrace\)
$4 \cdot \left( \frac{1}{2} % …

\(4 \cdot \left(\frac{1}{2} +\frac{3}{ 12 \cdot \left( 2 + \frac{1}{86 \cdot \left(\frac{1}{2} + 24 \right)} \right)} \right)\)

Depicting boundaries

The bounds of an integral can be enforced to appear above and below the integral symbol using the \limits command. This is the standard behaviour for sums, products and limits.

\sum_{i=1}^{n^2}(x+2)
\prod_{j=1}^{100}(3 \cdot x)
\lim_{x \rightarrow \infty}(14x^3 - 12)
\int\limits_{-12}^{4}(14x^3 - 12)

Don’t use \limits inline.

Set-builder notation

In certain situations, it is more adequate to use textual predicates or long function names within the set builder notation.

This is where \text{} comes into play.

\(\left\lbrace x \mid frequency(x) \geq 20\right\rbrace\)

\(\left\lbrace x \mid \text{frequency}(x) \geq 20\right\rbrace\)

$\left\lbrace x \mid \text{frequency} …

8 . Graphics

Including graphics 🖼️

To display graphics, we need the graphicx package.

\begin{figure}
    \includegraphics{<file path>}
    \caption[<short caption (table of
        figures)>]{<full caption>}
\end{figure}

Specifying the size:

\includegraphics[width=0.5\textwidth,
height=5cm]{<file path>}

Layout on the page

\begin{figure}[<position code>]

LaTeX places graphics automatically. With position codes, we can express our preferences (they can be combined as well).

code position
h here, if you don’t mind
t top of the page
b bottom of the page
p on its own page
H Here, for God’s sake!
(float package required)

Centred alignment

\begin{figure}[<position>]
    \begin{center}
        \includegraphics{<path-to-file>}
    \end{center}
\end{figure}

Alternatively:

\begin{figure}[<position>]
    \centering
    \includegraphics{<path-to-file>}
\end{figure}

Inserting graphics

  • In the directory exercises/graphics you can find an image file named latex-logo.png.
  • Include the figure in exercises/graphics/graphics.tex and place it exactly where you include it.
  • The image shall be centered.
  • Additionally, add a caption for the figure.
  • Adapt the width of the image to the width of the text (\textwidth).

9 . Tables

Basic structure 🗒️

For typographically pleasing tables, we use the booktabs package.

\usepackage{booktabs}
\begin{table}[<position>]
    \caption{<caption>}
    \begin{tabular}{<column definition>}
        % table content
    \end{tabular}
\end{table}

Positioning works just like with graphics.

Column definitions

\begin{tabular}{lrcl}
    % table content
\end{tabular}
letter meaning
l left-justified column
c centred column
r right-justified column

Vertical separator lines and double horizontal lines are frowned upon by typographers and should be avoided.

Table content

\begin{tabular}{lll}
    \toprule
    Column 1 & Column 2 & Column 3    \\
    \midrule
    Content a & Content b & Content c \\
    Content e & Content f & Content g \\
    Content i & Content j & Content k \\
    \bottomrule
\end{tabular}
  • Columns are separated by ’&’.
  • Rows are ended by ‘\\’.
  • \toprule, \midrule and \bottomrule structure the table.

The entire table

\begin{table}[h]
    \caption{Well-known programming languages}
    \begin{tabular}{lrcl}
        \toprule
        Language & Author            & Year & File extension \\
        \midrule 
        C++      & Bjarne Stroustrup & 1985 & .cpp           \\
        Java     & James Gosling     & 1998 & .java          \\
        Python   & Guido van Rossum  & 1991 & .py            \\
        \bottomrule
    \end{tabular}
\end{table}

@{} to the left and right of a column definition removes the padding of the corresponding column.

\begin{tabular}{@{}lrcl@{}} limits the row separators to the width of the table content

More comfort

The Tables Generator is a wonderful tool to quickly create tables of different formats.

Typesetting tables

  • The list in file exercises/tables/tables.tex stores information on a few modules of the WIAI faculty.
  • Transform the list into a table.
  • The table shall have colums for the name, the abbreviation (Kürzel) and the semester of the lectures.
  • Add a column with center-aligned text on the left side of the table in order to number the lectures.
  • Add a caption for the table.

Particularly long tables

Tables that exceed one page are simply cut off by tabular. A solution is offered by the longtable package:

\usepackage{longtable}
\begin{longtable}{<column definition>}
    \caption{<caption>}
    \label{<label>}
    % table content
\end{longtable}

Notes on longtable

\begin{longtable}{<column definition>}
    \caption{<caption>}
    \label{<label>}
    % table content
\end{longtable}
  • The longtable environment merges the tabular and table environments.
  • Caption and label can therefore be inserted directly under the table content.
  • As long as the booktabs package is used, its features are also provided in longtable.

Particularly wide tables

If you need a table to be wider than a page, you can display it in landscape orientation:

\usepackage{rotating}
\begin{sidewaystable}[<position>]
    \begin{tabular}{<column def.>}
        % table content
    \end{tabular}
\end{sidewaystable}

Colouring a table

\usepackage[table]{xcolor}
\begin{tabular}{lll}
    \toprule
    A & \cellcolor{yellow}yellow & cell \\
    A & \cellcolor{yellow!25}lighter yellow & cell \\
    \rowcolor[HTML]{FFDE21}
    A & yellow & row  \\
    \bottomrule
\end{tabular}
  • Use \cellcolor to color individual cells.
  • Use \rowcolor to color entire rows.
  • Color can be defined by name, percentage (e.g. yellow!25), or hex ([HTML]{...}).

Merge cells

\begin{tabular}{lll}
    \toprule
    Animal  & Food  & Size  \\
    \midrule
    horse   & hay   & large \\
    frog    & flies & small \\
    fooboar & \multicolumn{2}{c}{unknown} \\
    \bottomrule
\end{tabular}
  • \multicolumn{2}{c}{...} combines two columns into one.
  • The second argument specifies the alignment (and borders).

Line breaks in a cell

\usepackage{makecell}
\begin{tabular}{ll}
    \toprule
    Name & Description                          \\
    \midrule
    Cat & \makecell[l]{small \\ likes to sleep} \\
    Dog & \makecell[l]{loyal \\ needs walks}    \\
    \bottomrule
\end{tabular}
  • By default, \makecell centers its contents.
  • Use \makecell[l]{content} to left-align the content.

Fixed column width

The p{4cm} column automatically wraps text within 4cm.

\begin{tabular}{lp{4cm}}
    \toprule
    Item  & Description                 \\
    \midrule
    Chair & Four legs, one surface      \\
    Table & Like a chair but different  \\
    \bottomrule
\end{tabular}

An advanced example

\begin{table}[h]
    \begin{tabular}{llr}
        \toprule
        Structure   & \multicolumn{2}{l}{Access time complexity} \\ \cmidrule(r){2-3} & Average & Worst \\
        \midrule
        Stack       & $\mathcal{O}(n)$      & $\mathcal{O}(n)$      \\
        Binary tree & $\mathcal{O}(log(n))$ & $\mathcal{O}(n)$      \\
        AVL tree    & $\mathcal{O}(log(n))$ & $\mathcal{O}(log(n))$ \\
        \bottomrule
    \end{tabular}
\end{table}

Further resources

  • For tips on how to format tables — including what to align left, how to label columns and when to use borders — refer to the APA style guide:

🔗 Table guidelines

  • The booktabs package provides commands for high-quality tables:

🔗 Booktabs documentation

10 . References and footnotes

Footnotes 📎

Footnotes are automatically numbered consecutively, independent of sections.

The wild boar (\textit{Sus scrofa}), also 
known as the wild swine, common wild pig, 
or simply wild pig, is a suid native to 
much of Eurasia and North Africa, and has 
been introduced to the Americas and Oceania.
\footnote{\url{https://en.wikipedia.org/
wiki/Wild_boar}}

Cross-references

Manually (just don’t!)

As you can see in Figure 23, …

Using the \ref command:

\begin{figure}[H]
    \includegraphics % …
    \caption{Our mascot Fooboar}
    \label{fig:fooboar}
\end{figure}

As you can see in Figure 
\ref{fig:fooboar}, …

Assigning labels

Both cross-reference commands work with sections, figures, tables, listings, and equations, as long as you use correct labels.

Labels have to be unambiguous. For clarity, certain prefixes are common, and some packages use them to derive information.

fig: Figures tbl: Tables
sec: Sections subsec: Subsections
ch: Chapters itm: Enumeration items
eq: Equations lst: Source code listings

Cross-references

Using the cleveref package (with one ‘r’!):

\begin{figure}[H]
    \includegraphics % …
    \caption{Our mascot Fooboar}
    \label{fig:fooboar}
\end{figure}

Fooboar is a young and highly committed
boar (see \Cref{fig:fooboar}).

The \cref command automatically inserts suitable prefixes.

Things to consider

  • Terms inserted by \cref use the language specified with the document class (or babel):

    \documentclass[english]{article}
  • Apart from sections, referenced elements need captions (\caption{…}), and the captions have to be placed before the label.

  • For sectioning commands, the label is inserted directly after the section command.

    \section{Notes}\label{sec:notes}

Inserting footnotes

Inserting references

  • In file exercises/references/references.tex, replace In the figure and The following source code listing by references to the figure and to the source code listing.
  • Use the command \Cref for the references.
  • Make sure to add labels and captions to the elements that you want to create a reference for.
  • For source code listings, adding labels and captions is a bit different. Try to apply the knowledge you gained so far to retrieve the correct version of the \lstinputlisting command. Use the Internet, if necessary.

Configuring footnotes

The footmisc package provides additional options for the presentation of footnotes that can be activated by adding parameters to the \usepackage command.

% Reset the counter on each page:
\usepackage[perpage]{footmisc}

% Display footnotes in-line:
\usepackage[para]{footmisc}

% Use symbols instead of numbers:
\usepackage[symbol]{footmisc}

A few more things

  • It is recommended that you include the package hyperref before cleveref.
  • \cref can take multiple references at once, separated by commas.
\section{An introduction}
\label{sec:section1}
% …
Reference be made to 
\Cref{sec:section1,sec:section2,
sec:section3,sec:section5}.

11 . Source code listings

In-situ listings

The listings package provides a dedicated environment:

\section*{Haskell Magic}
Squares of all even % …
\begin{lstlisting}[language=Haskell]
[x^2 | x <- [1..200], even x]
\end{lstlisting}

External source code

Conveniently, listings offers an import command:

\section*{Simple Java Application}
\lstinputlisting[language=Java]{Test.java}
public class Test {
    public static void main(/*…*/) {
        System.out.println(/*…*/);
    }
}

Themes and styles

listings does not provide any themes by default, but can be configured extensively.

\begin{lstlisting}[
    language=Java,
    basicstyle=\footnotesize\ttfamily,
    breaklines=true,
    keywordstyle=\color{ForestGreen},
    commentstyle=\color{DarkGray},
    literate={ö}{{\"o}}1
]
% …
\end{lstlisting}

Have a look at the \lstset command for creating your own themes.

Further resources

Listings

  • Include the Java source code Source.java in the file source-code-listings.tex (mind the relative file path!).
  • Enable special characters like umlauts via the literate option.
  • Activate syntax highlighting by stating the programming language Java.
  • Number the code lines.
  • Set the basicstyle to a proper mono-spaced font (\ttfamily \small).
  • Change the keyword color to blue.
  • Remove the signs for spaces in strings.

If you have questions, try to consult the documentation of the listings package.

12 . Reference management

Citing in Alpha style ([style=alphabetic,backend=biber])
Citing in IEEE style ([style=ieee,backend=biber])

What do we need?

  • a bibliography file (hereafter .bib file) for storing references
  • Biber/BibLaTeX as an interface between the references and LaTeX

Preparing TeXstudio:

  • Bibliography > set type to BibLaTeX
  • Options > Configure TeXstudio > Generate > set standard for bibliography to Biber

What is this mysterious .bib file?

  • collection of references in BibTeX format¹
  • example content:
@article{turing1990, % the type of the document and an identifier for the \cite command
    title={The chemical basis of morphogenesis}, % information
    author={Turing, Alan Mathison},              % about
    journal={Bulletin of mathematical biology},  % the
    volume={52},                                 % literature
    pages={153--197},                            % work
    date={1990},                                 % follows
    publisher={Springer}                         % …
}

[1] Note: Even though we are working with BibLaTeX, our bibliography file adheres to the conventions of BibTeX, which is an alternative program. The name has been established for all kinds of things related to LaTeX citations. This is similar to the way we refer to online search by the name of one popular search engine.

BibLaTeX

  • Package for creating and designing bibliographies
  • Uses biber as a backend

Some well-meaning advice

You want the references to look professional?

Trust BibLaTeX’s default citation styles!

This conversely means: Avoid fiddling around with styles manually.

What you need

  • Include the BibLaTeX package in the preamble:
\usepackage[style=<citation-style>, 
backend=biber]{biblatex}
  • Include the .bib-file in the preamble:
\addbibresource{<bib-file>}
  • Generate the bibliography:
\printbibliography
  • BibLaTeX documentation: Link
  • BibLaTeX cheat sheet: Link

Changing the citation style

  • Built-in styles for direct use (z.B. authoryear, numeric, alphabetic)
  • additionally options for configurations and other styles (z.B. apa, ieee, chicago-authordate)
\usepackage[style=numeric, citestyle=ieee, 
backend=biber]{biblatex}

Two things are infinite: the universe and the assortment of citation styles.Unknown

Sorting entries

\usepackage[style=numeric, citestyle=ieee, 
sorting=nty, backend=biber]{biblatex}
Code Description
nty Name, Title, Year
nyt Name, Year, Title
nyvt Name, Year, Volume, Title
ydtn Year (descending), Title, Name

How is it used?

BibLaTeX adds some citation commands to LaTeX. In addition, we need the natbib package.

Code Description
\parencite{turing1990} [Turing, 1990]
\textcite{turing1990} Turing (1990)
\textcite[p. 159]
{turing1990}
Turing (1990, p. 159)

Citing with additional text:
\cite[<prefix>][<suffix>]{<source>}

An example

\usepackage[style=authoryear, 
maxnames=3, 
minnames=1, 
nohashothers=true, 
dashed=false, 
url=false, 
backend=biber]{biblatex}

An exemplary reference in the citation style above:

… in parentheses \parencite{thatcher2002} 
or simply as \textcite{thatcher2002} …
Finding ready-made BibTeX entries – University of Bamberg Library
Finding ready-made BibTeX entries – Google Scholar
Finding ready-made BibTeX entries – Google Scholar
Finding ready-made BibTeX entries – dblp.org

Creating and inserting references

  • Create a new BibTeX file called literature.bib in the exercises/literature folder.
  • Use Google Scholar or dblp.org to retrieve BibTeX references for the following \(\LaTeX\) handbooks:
    • Dilip Datta (2017): \(\LaTeX\) in 24 Hours. A Practical Guide for Scientific Writing.
    • Frank Mittelbach / Michel Goossens (2010): Der \(\LaTeX\)-Begleiter.
  • Add the BibTeX entries to the BibTeX file.
  • Assign unique and meaningful BibTeX keys.
  • Add the bibliography file to the project’s preamble.
  • Make use of the alphabetic bibliography style.
  • Cite the two handbooks in the file exercises/literature/literature.tex.
  • Ensure that the bibliography is listed.

Not: If the compilation fails, it may be helpful to remove all temporary files (….aux/bbl/blg/loc/out/pdf/soc/toc) and to compile again.

The University Library recommends …

  • reference management software (esp. Zotero) help to build a literature database, store quotations, and organize one’s own notes
  • support available from the library’s own reference management team: literaturverwaltung.ub@uni-bamberg.de
  • in Zotero: activate the plugin “Better BibTeX” (applies also if you are using biblatex)

💡 Further information

There are plenty of resources about the setup available online.

Setup for Zotero with Better BibTeX

  • Zotero:
    • install “Better BibTeX”
    • Tools > Plugins > enable Better BibTeX for Zotero
    • export your library from Zotero, set Better BibLaTex as format, and set keep updated to true
    • save the library in your LaTeX project archive and use it as the .bib-file

Demo: Referencing with Zotero and BibLaTeX

  • Hint: “Zotero Connector for Firefox” for easy import of BibTeX entries
  • First set up Zotero with Better BibTeX (see previous slide)
  • Open the reference source and click on the Firefox extensions
  • Run Zotero Connector and import the BibTeX entry into Zotero
  • Reference the source as usual according to the procedures already described

13 . Package in sight!

Creating an index

\usepackage{makeidx}
\makeindex
\begin{document}
\maketitle
\section{What is LaTeX\index{LaTeX}?}
LaTeX\index{LaTeX} is a typesetting
system\index{Typesetting system}.
\newpage \section{TeX\index{TeX} vs.
LaTeX\index{LaTeX}} It is based on
TeX\index{TeX}, an invention by 
Donald Knuth\index{Knuth, Donald}.
As TeX\index{TeX} is way more complex
syntactically than LaTeX\index{LaTeX},
LaTeX\index{LaTeX} is much more 
popular.
\printindex

Designing presentation slides

For slides, there is the beamer document class, as well as numerous templates and themes.

\documentclass{beamer}
\usetheme{Frankfurt}
\usecolortheme{seahorse}
\usepackage[utf8]{inputenc}

\begin{document}
\begin{frame} 
    \frametitle{Lemon sorbet}
    \framesubtitle{Incarnation of good?}
    \begin{definition}
        A lemon sorbet is a
        semi-frozen \textbf{dessert}
        on \textit{lemon} base.
    \end{definition}
\end{frame}
\end{document}
A (more modern) beamer example

Drawing images

TikZ (“TikZ ist kein Zeichenprogramm” — “TikZ is no drawing software”) is a powerful package for drawing vector graphics.

% …
\tikzstyle{every node}=[draw=black,thick,anchor=west]
\tikzstyle{selected}=[draw=red,fill=red!30]
\tikzstyle{dir}=[fill=gray!50]
\tikzstyle{relativeTo}=[fill=blue!70]
\begin{tikzpicture}[%
grow via
three points={one child at (0.5,-0.7) and
two children at
(0.5,-0.7) and (0.5,-1.4)},
edge from
parent path={(\tikzparentnode.south)
 |- (\tikzchildnode.west)}]
\node {/ or C:}
child { node {home}
  child { node {knut}
    child { node {pictures}}
    child { node {docs}
      child { node [dir] {latex}
        child { node [relativeTo] {main.tex}
        child { node [selected] {part1.tex}
      }
    }
  }
};
\end{tikzpicture}

Linguistics

The qtree package can render constituent-based parse trees:

\Tree [.S [.NP LaTeX ]
[.VP [.V is ] [.NP fun ] ] ]

Mathematical proofs

Logical tableaux can be renderd using the prftree package.

\begin{displaymath}
\prftree[l,r]{}{[comp$\_{ns}$]}
{
  \prftree[l,r]{}{[comp$\_{ns}$]}
  {
    \prftree[l,r]{}{[ass$\_{ns}$]}
    {
      -
    }
    {
      (\texttt{m:=a}, \sigma\_{\bot,\bot})
      \rightarrow \sigma\_{48,\bot}
    }
  }
  {
    \prftree[l,r]{}{[ass$\_{ns}$]}
    {
      -
    }
    {
      (\texttt{n:=b}, \sigma\_{48,\bot})
      \rightarrow \sigma\_{48,18}
    }
  }
  {
    (\texttt{m:=a; n:=b}, \sigma\_{\bot,\bot})
    \rightarrow \sigma\_{48,18}
  }
}
{
  \prftree[l,r]{}{}
  {
    \dots
  }
  {
    \textbf{[1]}\ (\texttt{LOOP}, \sigma\_{48,18})
    \rightarrow \sigma\_{6,6}
  }
}
{
  (\texttt{m:=a; n:=b; LOOP}, \sigma\_{\bot,\bot})
  \rightarrow \sigma\_{6,6}
}
\end{displaymath}

Other useful packages

Package Use case
xcolor colours
todonotes todo annotations and index
pdfpages embedding PDF files
subcaption Nested figures and fine-tuned captions
colortbl, tabularx, multirow, makecell Table tuning

14 . Getting help and information

Wikibooks

The LaTeX Wikibook offers numerous interesting articles and is available in English and German (among others).

CTAN

The “Comprehensive TeX Archive Network” is the central source for LaTeX packages and their documentation.

Overleaf

Overleaf is a collaborative online LaTeX editor.

It also offers a multiple tutorials and templates for different occasions (CV, theses, …): »Templates«.

StackExchange

Question-and-answer website for LaTeX.

TeXample

A collection of LaTeX examples, especially with TikZ.

Classic (source)
More classic (source)
Different (source)

Fachschaft WIAI

If you have any other questions or problems, just come over or write us an e-mail!

📍WE5/02.104
☎️0951 863 1219
📧fachschaft-wiai.stuve@uni-bamberg.de

A short feedback round

  • What did you like?
  • What could we have done better?
  • What would you have wished for?

wiai.de/latex-feedback

How to use this presentation

Imprint and privacy policy