LATEX Weekend

A Fachschaft WIAI workshop. Created by Anika Amma, Evelyn Fradtschuk, Florian Knoch, Christian Kremitzl, Fabian Lamprecht, Bernhard Luedtke, and Anna Sauer.

What is LATEX?

Classic Word document
Classic LaTeX document

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
Classic Word document
Classic LaTeX document

Typography

Macro typography

  • type area
  • line length and leading
  • placement of headings in whitespace
  • placement of images and tables
  • widows and orphans
  • even grey value
Type area construction by Villard (source)

Typography

Micro typography

  • ligatures
  • kerning
  • real italics, small capitals, font sizes …
  • word spacing
Font styles:
straight, oblique, italic
Font sizes:
small, small scaled up, large

Further advantages

  • much better default settings
    than any other word processor
  • structured workflow
  • reliable undo
  • easy versioning
  • independence of proprietary software
  • source code and output
    readable in the long term
  • easy cooperation with other software

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. How does LaTeX work?
  3. Basic structure of a LaTeX document
  4. Project structure
  5. Lots of features
  6. Reference management
  7. Outlook

How does
LATEX work?

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
How to get the final document

What do we need?

Editor

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

TeXstudio, TeXMaker

Compiler

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

MiKTeX, MacTeX, TeX Live

Backslash

You get the backslash by pressing

AltGr + ß (Windows/Linux)

Alt + Shift + 7 (MacOS)

Optional parameters

Square brackets may contain different numbers of optional parameters:

\usepackage[utf8]{inputenc}
% configures the text encoding

\documentclass[a4paper,12pt]{article}
% configures the document class

\includegraphics[width=12cm,height=4cm]{image.png}
% embeds the image file "image.png"

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 \\
Geburtsdatum: \\ % TODO: insert
Geburtsort: Milwaukee, Wisconsin
% profile end

Shortcuts: Ctrl + T and Ctrl + U

Software installation

Please install the compiler first (MikTeX on Windows, MacTeX on MacOS, TeX Live on Linux), followed by the editor. In this workshop, we use TeXstudio.

First steps with LaTeX

  • If necessary: Install now!
  • Download the project archive from the VC. Unzip the archive.
  • Open the file main.tex in TeXstudio. It is located in the root directory of the archive.
  • Navigate to the command settings of TeXstudio: Options -> Configure TeXstudio… -> Commands
  • Change the compiler command for PdfLaTeX to: pdflatex -synctex=1 -interaction=nonstopmode -shell-escape %.tex
  • Compile main.tex by pressing .
  • What happened to the folder that contains the file?

Basic structure of a LATEX document

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]{scrartcl}
  • scrartcl, article for short documents
  • scrreport, report for longer documents
  • scrbook, book for books
  • beamer for presentations

Packages

\usepackage[<options>]{<package_name>}
  • Packages provide additional commands and functionalities.
  • There are different packages for different use cases (e. g., mathematical formulas, lists, …).
  • Before they can be used, they have to be included within the preamble.

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.

Languages

A document can use multiple languages at once:

\usepackage[ngerman, swedish, russian, 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{russian}
\today
\selectlanguage{greek}
\today
\selectlanguage{english}
\today

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.

Reserved characters

Some characters do things in LaTeX:

# $ % ^ & _ { } ~ \

50% is one half.

Solution: prefix with ‘\’:

50\% is one half.

Does not work for ‘\\’, we will see a solution for this later.

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}

Sections and chapters

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}

Front matter

\title{The World of Truffles}
\author{Fooboar Rüssel \\ Fachschaft WIAI\thanks{WIe AIn Profi},
        Otto-Friedrich-Universität Bamberg}
\date{\today}
\begin{document}
\maketitle
\end{document}
  • The values for the entries are stored in the preamble.
  • \maketitle typesets the front matter 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 \\ Fachschaft
WIAI\thanks{WIe AIn Profi},
Otto-Friedrich-Universität Bamberg}
\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}

Table of contents

\tableofcontents
  • automatic numbering
  • very configurable (enumeration characters and depth, automatic naming, …)
  • chapters and (sub-)sections with an asterisk (*) are hidden from the table of contents: 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}

Other indices

List of figures and list of tables

\listoffigures
\listoftables
  • inserts the corresponding index wherever it is called
  • lists the caption of each figure or table by default, but you can also state a special list entry

Structure your document and text

  • 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. Compile the document.
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage[hidelinks]{hyperref}
  • 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.
  • Finally, comment out the preamble, the document environment, and the table of contents. Only this way, your solution can be embedded in the script itself.

Project structure

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 and front matter
  • includes separate sections with
    \input{path/to/file} or
    \include{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.

% …

input or include?

\input{path/to/file}
  • file extension .tex may be added
  • nesting possible: nested files can again be embedded using \input{}
  • file is added to the resulting document without a page break
\include{path/to/file}
  • file extension .tex must not be added
  • no nesting possible
  • each subfile starts a new page in the resulting document
  • advantage for larger projects: \includeonly{file1,file2,...} can be used in the preable to compile only certain subfiles (the entire project has to be compiled at least once before)

Specifying file paths 👣

  • important for \input{} and \include{}, later also for pictures
  • file and folder structure = tree structure 🌳

Specifying file paths 👣

Absolute paths

  • path from the root directory to a file
  • the direcories are separated by special characters:
    • in UNIX: /
    • in Windows: \

absolute path for main.tex

  • UNIX: /home/knut/docs/latex/main.tex
  • Windows: C:\knut\docs\latex\main.tex

In LaTeX, you have to use UNIX-style paths. Therefore, we will use those from here on.

Specifying file paths 👣

Relative paths

  • path from somewhere in the tree to a certain file
  • shorter + less typing!
  • with \input{} and \include{}, you can specify the path relative to the main file

Relative path
from main.tex to part1.tex

./part1.tex

A single dot ‘. in a relative path represents the current folder (in this case: latex). It is optional, you could also write part1.tex here.

Specifying paths 👣

Relative paths

Relative path from main.tex to part1.tex in subfolder

./sections/part1.tex

Specifying paths 👣

Relative paths

Relative path from main.tex in its own subfolder to part1.tex in another subfolder

../sections/part1.tex

Two dots ‘.. represent the parent folder of the current folder (in this case: latex, parent of main).

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.

Outsourcing the preamble

What do you think happens when we outsource the preamble into its own subfile?

Will the document compile?

Yes, it will!
A simple way of keeping the main file even more organised.

A structured project

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

  • Extract the sections into their own files (section1.tex, section2.tex, and section3.tex) and insert them using the \include command.
  • Which command is rendered superfluous by \include?

Special characters

Spaces

  • normal space dividing words: space bar
  • non-breaking space: ~
  • thin space: \,
  • many other widths available
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.

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: \@.␣

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

Hyphenation

Most of the time, LaTeX hyphenates words correctly, if the correct language is configured. But you can also intervene manually:

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.

Quotation marks

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, but most of the time it’s the same characters, only combined differently.

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

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 & symbols

The same is true for special characters: They can either 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.

Special characters & symbols

Math mode

Some special characters and symbols require a math environment:

% greek letters (π Σ δ)
$\pi \Sigma \delta$

% dagger/obelisk/obelus (†)
$\dagger$

Special characters & symbols

Euro (€)

  • eurosym package
  • \euro command
Using LaTeX costs 0 \euro.

Special characters & symbols

Detexify to the rescue! ⛑️

Insert special characters

From now on, compile the file main.tex to see your changes appear in the script itself (in this task, see section “Übung 5”).

  • Replace the spaces in exercises/special-characters.tex within the abbreviations (“z. B.”, “u. a.”) by thin spaces. On top of that, replace the space before the word Euro by a thin space.
  • Replace the hyphens by a dash (--).
  • Add an exclusive hyphenation in the word Studierendenausweis after Studierenden-.
  • Replace Euro by a Euro sign.

Text Markup

Emphases

The easiest way of emphasising in continuous text is the semantic command \emph{} that can also be nested:

\emph{If you have a whole bunch of 
important text with some \emph{even more 
important Text} hidden inside it, 
you can use nested emphases.}

Optical highlighting

specifies exactly how to format the text:

Name Befehl
Bold (bold face) \textbf{important}
Italics (italics) \textit{important}
Small caps \textsc{important}
non-proportional (teletype) \texttt{important}
slanted \textsl{important}
underlined \underline{important}
subscript \textsubscript{…}
superscript \textsuperscript{…}

Nesting emphases

Possible if the font contains the exact font style:

\textbf{Very
    \textit{Important
        \textsc{Stuff}
    }
}

Font size

Some well-meaning advice: Better Call Saul LaTeX!

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.

Font size

normalsize

  • used for continuous text paragraphs
  • default: 10pt
  • can be modified in the preamble:
\documentclass[12pt]{article}

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

Font size

Manual configuration possible

\fontsize{<fontsize>}{<lineheight>}
\selectfont

This is text in normal font size.

\fontsize{1cm}{0.9cm}\selectfont
This is a ginormous passage.

\normalsize
Back to normal.

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

Emphasising text

  • Emphasise the words Rekursion and rekursiv in exercises/text-markup/markup.tex using \emph{…}.
  • Make the URL in the text clickable.
  • Of course, you can also experiment with the other text markup possibilities. However, remove them afterwards, if you want to have a clean document.

Formatting paragraphs

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

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}

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.

Nested lists

\begin{compactitem}
  % …
  \item vegetables \begin{compactitem}
    \item crushed tomatoes
    \item carrots
    \item peas
    \item onions
  \end{compactitem}
  \item herbs \begin{compactenum}
    \item oregano
    \item basil
    \item rosemary
  \end{compactenum}
  % …
\end{compactitem}

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.

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

Adding enumerations

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

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
\sqrt{16} \(\sqrt{16}\)
\frac{3}{4} \(\frac{3}{4}\)
e^{\pi} \(e^{\pi}\)
\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}\)

^{…} and _{…} make the content between the braces appear as sub- or superscripted.

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.

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*}).

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 \mathrm{} comes into play.

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

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

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

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}\)
Formula to solve quadratic equations \(x_{1,2} = - \frac{p}{2} \pm \sqrt{\left(\frac{p}{2}\right)^2 - q}\)
Another formula to solve quadratic equations \(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

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

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

Source code listings

Installation 🖥️

Minted, another LaTeX package, is very useful to display source code. It requires the Python programming language.

As soon as Python is installed, we can download the corresponding Python package Pygments using a command prompt:

pip install Pygments

Add the LaTeX package and we are good to go:

\usepackage{minted}

Compiler settings

We need to pass the additional flag --shell-escape to our compiler in order to use minted.

In TeXstudio, go to Options → Configure TeXstudio → Commands and add the flag in the PdfLaTeX row before %.tex:

pdflatex -synctex=1 -interaction=nonstopmode --shell-escape %.tex

Listings within LaTeX documents

Within a dedicated environment:

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

Directly inline:

\section*{An HTML Example}
A headline is denoted the following way:
\mint{html}|<h2>LaTeX at University</h2>|

External source code

We can avoid redundancy by including source code directly from its source file.

\section*{Simple Java Application}
\inputminted{java}{Test.java}
public class HelloWorld {
    public static void main(/*…*/) {
        System.out.println(/*…*/);
    }
}

Configuring minted

Optional parameters allow us to activate line numbers, automated line breaks, and syntax highlighting based on numerous color schemes.

\usemintedstyle{monokai}
\begin{minted}[
linenos=true,
breaklines=true,
]{javascript}
    % ...
\end{minted}

🔗 introduction and official documentation

Listing source code

  • In the directory exercises/source-code-listings you can find a file named Source.java, which we want to include in our document.
  • Include the java code in the file source-code-listings.tex. (Keep in mind that the file path is relative to the main LaTeX document, i. e., to main.tex.)
  • Number the code lines.
  • Use the theme native.
  • Change the background colour to dark blue.
  • Now only include lines 5 to 7.
  • Delete the spaces at the beginning of the lines by using a suitable option (Hint: The documentation speaks of gobble).
  • If you have questions, try to consult the documentation of the Minted package.

Graphics

Including graphics 🖼️

To display graphics, we need the graphicx package.

\begin{figure}
    \includegraphics{<file path>}
    \caption[<short caption>]
            {<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.
  • 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).

Tables

Basic structure 🗒️

For typographically pleasing tables, we use the booktabs package.

\usepackage{booktabs}
\begin{table}[<position>]
    \begin{tabular}{<column definition>}
        % table content
    \end{tabular}
    \caption{<caption>}
\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]
    \begin{tabular}{lrcl}
        \toprule
        Language & Author            & Year & Version \\
        \midrule 
        C++      & Bjarne Stroustrup & 1985 & C++ 17  \\
        Java     & James Gosling     & 1998 & 13      \\
        Python   & Guido van Rossum  & 1991 & 3.8.0   \\
        \bottomrule
    \end{tabular}
    \caption{Well-known programming languages}
\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

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>}
    % table content
    \caption{<caption>}
    \label{<label>}
\end{longtable}

Notes on longtable

\begin{longtable}{<column definition>}
    % table content
    \caption{<caption>}
    \label{<label>}
\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}

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}

🔗 Booktabs documentation

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.

References and footnotes

Footnotes 📎

\usepackage{hyperref}

Footnotes are automatically numbered consecutively, independent of sections.

(Here, hyperref is used for the \url command, it is not necessary for footnotes per se.)

The wild boar (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}}

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}

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{img:fooboar}
\end{figure}

As you can see in figure 
\ref{img: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{img:fooboar}
\end{figure}

Fooboar is a young and highly engaged
boar (see \cref{img: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}

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

Inserting footnotes

  • Make the text Stand März 2021 in file exercises/footnotes/footnotes.tex appear as a footnote.
  • Additionally, insert a clickable URL that leads to the download page for the Java Development Kit (https://www.oracle.com/java/technologies/javase-downloads.html).

Inserting references

  • In file exercises/references/references.tex, replace in der Abbildung and Das nachstehende Quelltext-Listing by references to the figure and to the source code listing.
  • Use the command \cref for the references.
  • Make sure to add labels to the elements that you want to create a reference for.
  • To do so, wrap the source code listing in a listing environment.
  • Additionally, add a caption to the source code listing.

Reference management

What do we need?

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

What is this mysterious .bib file?

  • collection of references in BibTeX format
  • example:
@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
    year={1990},                                 % follows
    publisher={Springer}                         % …
}

How is it used?

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

  • Citing a source: \cite{<source>}
  • Citing a page: \cite[p. 15]{<source>}
  • Citing with additional text:
    \cite[<prefix>][<suffix>]{<source>}
  • Referencing the .bib file: \bibliography{<.bib file>}
  • Choosing a citation style:
    \bibliographystyle{<citation style>}

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

Citing in Alpha style
Citing in Alpha style
Citing in Natdin style
Citing in Natdin style
Finding ready-made BibTeX entries – University of Bamberg Library
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 – Google Scholar
Finding ready-made BibTeX entries – Google Scholar
Finding ready-made BibTeX entries – Wikipedia
Finding ready-made BibTeX entries – Wikipedia
Finding ready-made BibTeX entries – Wikipedia
Finding ready-made BibTeX entries – Wikipedia

Creating and inserting references

  • Use Google Scholar to retrieve BibTeX references for the following \(\LaTeX\) handbooks:
    • Leslie Lamport (1994): \(\LaTeX\). A Document Preparation System.
    • Dilip Datta (2017): \(\LaTeX\) in 24 Hours. A Practical Guide for Scientific Writing.
    • Frank Mittelbach / Michel Goossens (2012): Der \(\LaTeX\)-Begleiter.
  • Compare the entries with the results that dblp.org finds for the same titles.
  • Create a new BibTeX file called literature.bib in the exercises/literature folder.
  • Add the BibTeX entries to the BibTeX file. For this, select your preferred source among Google Scholar and dblp.
  • Assign unique and meaningful BibTeX keys.
  • Include the BibTeX file in a suitable location, where later on the references should be listed.
  • Cite the three handbooks in the file exercises/literature/literature.tex.
  • Make use of the natdin bibliography style.

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}

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 {/ oder 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

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)
Classic (source)
More classic (source)
More classic (source)
Different (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 did you wish for?

How to use this presentation