0 . First steps with LATEX

Digression: Opening a command prompt

  • For the following tasks, we are going to need a command prompt.

  • It can be opened in different ways, depending on your operating system.

  • Windows: Press the Windows key and type in cmd, press Enter.

  • MacOS: Press the Command key and the space bar simultaneously, then type in Terminal and double click on Terminal.

  • Linux: Press Ctrl + Alt + T.

Installing the compiler

  • The compiler translates our LATEX code into a properly formatted PDF document.

  • Depending on your operating system, different compilers are available:

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

Installing the editor

  • An editor can be downloaded once the compiler has been installed.
  • For editing LaTeX documents, any text editor works fine, e. g., Notepad++ or VSCode.
  • For beginners, we recommend TEXstudio due to its LaTeX-specific features.
  • Download and install TEXstudio.

Compile the script for the first time

  • Download the project archive from the VC.
  • Unzip the archive.
  • Open the file main-exercises.tex in TEXstudio. It is located in the root directory of the archive.
  • Compile main-exercises.tex by pressing
  • A few new files will be generated by the compilation.

Windows users: 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.

LATEX Weekend

A Fachschaft WIAI workshop. Presented by Jessica Klarmann, Jannik Kiesel, Florian Knoch, Theresa Knoll, and Hannah Rattenberger.

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

Reasons for using LaTeX: macrotypography

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

short & tight

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

normal length and tight leading

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

long lines and tight leading

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

short & medium

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

normal length and leading

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

long lines and medium leading

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

short & loose

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

normal length and loose leading

This paragraph shows the effect of varied line heights in combination with varied line lengths. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph. For this purpose, a little more text is needed to make it look like an actual paragraph.

long lines and loose leading

Reasons for using LaTeX: microtypography

☹ slanted (distorted)

☺ straight

☺ italic (separate font)

☹ small font scaled up

☺ separate appropriate fonts

☹ big font scaled down

Reasons for using LaTeX: plaintext

  • reliable undo
  • easy versioning
  • independence of proprietary software
  • source code readable in the long term
  • easy cooperation with other software
  • no distraction by formatting or embedded media

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

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

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

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)

3 . 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]{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.

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

  • 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[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 speled 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}

Before we can continue …

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. (In TeXstudio, comments can be achieved by the shortcut Strg + T.)

We will learn in the following chapter why this is the case.

4 . 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
  • 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.

% …

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-skript). 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.

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.

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.

A structured project

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?

5 . 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, however, manual intervention is necessary.

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

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.

6 . Text Markup

Emphases

Continuous text can be emphasized with \emph{}:

\emph{Emphasize important 
\emph{and even more important} text}

Furthermore, optical highlighting can be used.

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

Emphasising text

  • Emphasise the words Recursion and recursive 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.

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

7 . 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 a unordered list for the ingredients and a 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.

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

8 . 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}\)
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}, \text{odd}(x) \}\)
Elimination \(\neg\exists x\) \(\neg\exists x . p(x) \Leftrightarrow \forall x . \neg p(x)\)

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

9 . 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).

10 . 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 & Filename extension \\
        \midrule 
        C++      & Bjarne Stroustrup & 1985 & .cpp    \\
        Java     & James Gosling     & 1998 & .java    \\
        Python   & Guido van Rossum  & 1991 & .py      \\
        \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

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

11 . 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 (\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 engaged
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

  • Make the text March 2023 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 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 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}.

12 . 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 an author: \citeauthor{<source>}
  • 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 Natdin style
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 (2012): Der \(\LaTeX\)-Begleiter.
  • Add the BibTeX entries to the BibTeX file.
  • Assign unique and meaningful BibTeX keys.
  • Include the BibTeX file in a suitable location, where later on the references should be listed.
  • Cite the two handbooks in the file exercises/literature/literature.tex.
  • Make use of the plain bibliography style.

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

  • In the directory exercises/source-code-listings you can find a file named Source.java.
  • Include it 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-exercises.tex.)
  • Enable special characters 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.
  • Don’t show special characters for spaces in strings.

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

14 . 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 {/ 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

15 . 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 did you wish for?

How to use this presentation

Imprint and privacy policy