Content from Introduction to LaTeX and Overleaf
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How can I write and render a LaTeX document?
- How can I use Overleaf to write and render a LaTeX document?
Objectives
- Demonstrate how to create a new project in Overleaf.
- Become familiar with the Overleaf interface.
What is LaTeX
LaTeX is a typesetting language, useful for combining text with mathematical equations, figures, tables, and citations, among other things.
Unlike common word processors like Microsoft Word or LibreOffice Writer, LaTex is a markup language, meaning that formatting (including bold text, bullet points, and changes in font size) is indicated by the use of commands, special characters, or environments.
In order to produce the actual document, this mark-up text must be compiled. Errors in the mark-up can either be non-fatal, meaning the document will compile with some warnings; or fatal, meaning the document will fail to compile.
Our first Overleaf Project
There are several ways to write LaTeX documents, but we’ll be using Overleaf, a cloud-based LaTeX editor. This has the advantage of being accessible from any computer with an internet connection, without the need to install any additional software. As part of the preparation for this workshop, you should have registered for an account on Overleaf.
We’ll start by creating a new, ‘Blank’, project in Overleaf by clicking on the large green button that says ‘New Project’ in the top left corner of the screen. This will open a drop-down menu with a number of options. We’ll select ‘Blank Project’ from this menu. Name the project ‘LaTeX Workshop’ and click ‘Create’.
The Overleaf Interface
Once the project is created, you’ll see that it isn’t quite blank. There are four main panels when you open a new project in Overleaf:
- The File Navigator on the top left, which shows all of the files in your project.
- The File Outline on the bottom left, which shows the structure of the current file.
- The Text Editor in the middle, where you can write your LaTeX code.
- The Preview Pane on the right, which shows a preview of the compiled document.
You’ll notice that our project isn’t quite blank, as we have a file
called main.tex
open in the text editor with some LaTeX
code already written. This is a basic LaTeX document, with some of the
minimum requirements for a LaTeX document.
The Main Menu
When we want to switch projects or create a new one, we can use the main menu at the top of the screen, which is indicated by a small “house” icon. Clicking on this icon will take us back to the main landing page for overleaf, where we initially created our project.
We can see now in the section “All Projects” that our new project, “LaTeX Workshop”, is listed there, that we are the owner, and that it was just recently modified. We can click on the project name to open it again.
Inline instructor notes can help inform instructors of timing challenges associated with the lessons. They appear in the “Instructor View”
Challenge 1: Create a new project, then delete it
See if you can create a new project in Overleaf. Name it “A test project”. Then close the project and reopen the “LaTeX Workshop” project. Finally, delete the “A test project” project.
Creating a new project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- Click the “New Project” button.
- Select “Blank Project” from the drop-down menu.
- Enter in “A test project” as the project name.
- Click “Create”.
Closing and reopening the “LaTeX Workshop” project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- Click on the “LaTeX Workshop” project to reopen it.
Deleting the “A test project” project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- Click the “trash can” icon next to the “A test project” project.
- Confirm that you want to delete the project.
Challenge 2: Copy your current project, then delete it
See if you can create a copy of your current project “LaTeX Workshop” in Overleaf. Name it “A copy project”. Then close the project and reopen the “LaTeX Workshop” project. Finally, delete the “A test project” project.
Creating a copy project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- For the “LaTeX Workshop” project, navigate to the right column “Actions”.
- Click on the first button, the “copy” button, in the “Actions” column for the “LaTeX Workshop” project.
- Enter in “A copy project” as the project name.
- Click “Copy”.
Closing and reopening the “LaTeX Workshop” project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- Click on the “LaTeX Workshop” project to reopen it.
Deleting the “A copy project” project:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- Click the “trash can” icon next to the “A copy project” project.
- Confirm that you want to delete the project.
Challenge 3: Three ways to download your project as pdf
See if you can download your new project “LaTeX Workshop” in Overleaf as a pdf file. In your current project “LaTeX Workshop”, navigate to the Preview Pane on the right. At the panel bar for the Preview Pane, find the button to download a pdf. If you have figured out the described way for downloading the pdf, try to find two alternative options on how to save your project as a pdf.
Option A as described in the task:
- In “LaTeX Workshop”, navigate to the Preview Pane on the right.
- At the panel bar for the Preview Pane, there is a button with an arrow pointing downwards.
- If you hover over this button, it displays “Download PDF”.
- Click on that button and a pdf of your current project “LaTeX Workshop” will be downloaded.
Option B:
- In “LaTeX Workshop”, click on the top left icon which contains the Overleaf symbol with the word “Menu”.
- The Menu sidebar will open on the left.
- In the first paragraph “Downloads”, click on the “pdf” button on the right to download your current project “LaTeX Workshop”.
Option C:
- Click the “house” icon on the top menu bar to return to the main Overleaf page.
- In “All projects”, you can find your project “LaTeX Workshop”.
- Navigate to the column “Actions” on the right side.
- If you hover over the third button, it says “Download PDF”.
- Click on this button to download your current project “LaTeX Workshop”.
Key Points
- We can use Overleaf to edit and render LaTeX documents.
- An Overleaf project can contain many files.
Content from File Structure
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- What is the basic structure of a LaTeX document?
- How do I see what my LaTeX document looks like when it’s rendered?
Objectives
- Become familiar with the basic structure of a LaTeX document.
- Use Overleaf to render a LaTeX document into a PDF.
- Identify how to add special characters to a LaTeX document.
Editing the Document
We can edit the main.tex
file by clicking on it in the
File Navigator. This will open the file in the text editor.
Let’s edit some of the provided code to create our first LaTeX
document.
LATEX
\documentclass{article}
\begin{document}
Hello World!
This is my first LaTeX document.
\end{document}
Callout
Errors happen! Check that you have entered each line in the text file exactly as written above. Sometimes seemingly small input changes give large changes in the result, including causing a document to not work. If you are stuck, try erasing the document and copying it fresh from the lines above.
Looking at our document
Our first document shows us the basics. LaTeX documents are a mixture of text and commands.
-
Commands start with a backslash
\
and sometimes have arguments in curly braces{}
. - Text is what you want to appear in the document and requires no special formatting.
Let’s look at the commands we’ve used so far:
-
\documentclass{article}
: This command tells LaTeX what kind of document we are creating. (We might also use this command to instruct LaTeX to use a specific font size, paper size, or other document settings - more on this later!) -
\begin{document}
and\end{document}
: These commands mark the beginning and end of the document body. These commands are required in every LaTeX document and create the document body.
Callout
You can have multiple \begin{...}
and
\end{...}
pairs in a single LaTeX document, but you must
have exactly as many \begin{...}
commands as
\end{...}
commands.
Everything before the \begin{document}
command is called
the preamble. The preamble is where you set up the document,
including the document class, title, author, and any other settings you
want to apply to the entire document.
Comments
We can add comments to our document by using the %
character. Anything after the %
on a line is ignored by
LaTeX. As in any other programming language, comments are useful for
explaining what the code is doing. We’ll start incorporating comments
into our document going forward to explain some of the specifics of the
LaTeX code we’re writing.
As we go, you should use your version of the document to add your own comments as a way of taking notes on what you’re learning, and to act as a reference for yourself in the future!
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
Hello World!
This is my first LaTeX document.
\end{document}
Going forward, the examples we provide will not always include comments, but you should add them to your document as you see fit.
Rendering the Document
In your Overleaf project, click the green Recompile button to render the document. This will generate a preview of the document in the right-hand pane.
Callout
There are many shortcut keyboard commands that you can use to speed
up your work in Overleaf. When we want to render the document, we can
use Ctrl + S
or Ctrl + Enter
(Windows) or
Cmd + S
or Cmd + Enter
(Mac). This will save
the document and render it in one step.
Paragraphs
Note that we have an empty line between our two lines of text. This is important in LaTeX, as this indicates a new paragraph. Let’s try removing the empty line and recompiling the document to see what happens.
You should see that the two lines of text are now displayed on the
same line. This is because LaTeX treats the two lines as part of the
same paragraph. If you want to start a new paragraph, you need to leave
a blank line between the two paragraphs. Instead of using an empty line,
there is also the command \par
that leads you to the same
result of creating a new paragraph. More on this in one of the
challenges below.
Special Characters
You’ve probably noticed by now that the characters \
,
{
, and }
are special characters in LaTeX.
There are others though, such as $
, %
,
&
, #
and ^
. These characters
tend to be much less common in text, but you can use them by “escaping”
them with a backslash. For example,
-
\%
produces%
-
\&
produces&
-
\#
produces#
-
\^
produces^
and so on.
What about the \
character?
The \
character is used to escape other characters in
latex, so it’s not possible to escape it in the same way. Instead, you
can use \textbackslash
to produce a backslash in your
document.
Callout
Sometimes, special characters can, unintentionally, conflate with
characters that are used after that special character. You can prevent
that by typing {}
directly behind your special character.
The following LaTeX code gives you an example:
Errors, Warnings and the Log
Inevitably, everyone makes mistakes when writing LaTeX documents. When you recompile your document, you might not see any changes in the preview pane. This could be because there is an error in your document. If there is an error, you will see a red number next to the “Recompile” button over the “Logs and output files” button. You will also see certain lines highlighted in red in the text editor, along with a suggestion of what the error might be.
Let’s introduce an error into our project to see what this might look
like. Let’s introduce a typo into the documentclass
command
by changing it to documnetclass
. When we recompile the
document, we can see our errors:

And if we click on the “Logs and output files” button, we can see a more detailed error message:

We can see similar messages when hovering over the small red circle next to the error in the text editor:

We’ll look more into how we can read and fix errors in a later episode.
Fixing Errors
Our tiny typo seems to have caused quite a number of issues! This can happen, the important thing is to read the error message and try to understand what it’s telling you. In this case it says:
Undefined control sequence. ./main.tex, 2
The compiler is having trouble understanding a command you have used. Check that the command is
spelled correctly. If the command is part of a package, make sure you have included the package
in your preamble using \usepackage{...}.
In order to diagnose the issue, we can first look at the name of the
message. In this case, it’s Undefined control sequence
.
This means that LaTeX doesn’t recognize the command we’ve used.
Specifically, it says, this undefined sequence is on line 2 of the
main.tex
file. We can then look at the line and see that
we’ve made a typo in the \documentclass
command.
As soon as we fix this typo and recompile our document, we should see the preview pane update and all of the remaining errors disappear.
Callout
The subsequent errors, talking about “missing begin document”, and “font size command not defined” are all cascading errors from the initial error. When LaTeX encounters an error, it can’t continue to compile the document, so it stops and reports the error it found. This can sometimes lead to multiple error messages, but generally it’s important to fix the first error first, as this will often resolve subsequent errors.
Challenges
Challenge 1: What’s wrong with this document?
There is an error in the following LaTeX document. Can you find it?
(Feel to make a new project in Overleaf to test this out!)
Each section of a LaTeX document must be enclosed in a pair of
\begin{...}
and \end{...}
. This document is
missing the \begin{document}
command.
Challenge 2: Displaying Special characters.
How would I display the following text in a LaTeX document?
5 is greater than 3 & 2 is less than 4. This is 100% true.
Challenge 3: Paragraphs with
\par
.
In the section about Paragraphs from above we learned that empty
lines are important to create paragraphs. However, there is also a LaTeX
command called \par
which might be of help for us. Consider
the LaTeX code below. Can you already guess which of these options
prints Hello World! and This is my first LaTeX
document. in two separate lines? (Feel to make a new project in
Overleaf to test this out!)
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
% Option A
Hello World!
This is my first LaTeX document.
% Option B
Hello World! This is my first LaTeX document.
% Option C
Hello World! \par This is my first LaTeX document.
% Option D
Hello World! \par
This is my first LaTeX document.
\end{document}
The command \par
initiates a new paragraph for us even
if we write text in just one line (see Option C). Solely, Option B out
of all four options does not create the intended new paragraph as
neither an empty line nor \par
is used. Moreover, Option D
gives us the same result as Option A and Option C, although we used
both, \par
and an empty line.
Challenge 4: One line of code with paragraphs and special characters.
How would I display the following text in a LaTeX document but using just one line of code?
Hello World! This is my first LaTeX document.
Now, I know how to initiate paragraphs without an empty line.
Even more, I can write # and ^ correctly using LaTeX.
We need to use \par
to initiate a new paragraph without
using a new line of code. Moreover, we need to use escapes before each
of the special characters. The following LaTeX code will display the
text correctly:
Key Points
- We can use Overleaf to edit and render LaTeX documents.
- The
%
character is used to add comments to a LaTeX document. - LaTeX documents are a mixture of text and commands.
- Commands start with a backslash
\
and sometimes have arguments in curly braces{}
. - We can view errors by either clicking on the “Logs and output files” or hovering over the red circle in the text editor.
After this episode, here is what our LaTeX document looks like:
Content from The Structure of a Document
Last updated on 2025-04-30 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How are LaTeX documents structured?
Objectives
- Identify the different kinds of section commands in LaTeX.
- Create a list within a LaTeX document.
Sections
In a word processor, you might use headings to organize your document.In LaTeX, we’ll use the section commands:
\section{...}
\subsection{...}
LaTeX will handle all of the numbering, formatting, vertical spacing, fonts, and so on in order to keep these elements consistent throughout your document. Let’s add sections to our document.
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
Hello World!
This is my first LaTeX document.
% The section command automatically numbers and formats the section heading.
\section{Sections}
I can add content to my first section!
% The subsection command does the same thing, but for sections within sections.
\subsection{Subsection}
I can put a subsection inside my first section.
\section{Second Section}
And this text will go into another section.
\end{document}
You should have something that looks like this:
Callout
There are many different section commands in LaTeX, including
\subsubsection{...}
, \paragraph{...}
,
\chapter{...}
, and more. Each of these commands will create
a new section heading with a different level of indentation and
numbering.
Some of these commands are only available in certain document classes, so be sure to check the documentation for the class you are using.
Lists
In LaTeX, as in markdown, there are two types of lists: ordered and
unordered. They are both defined with \begin{...}
and
\end{...}
commands, as we saw with the document body. Let’s
add an ordered list to our document.
We’ll replace our “Second Section” with one for “Lists” and add an ordered list:
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
Hello World!
This is my first LaTeX document.
% The section command automatically numbers and formats the section heading.
\section{Sections}
I can add content to my first section!
% The subsection command does the same thing, but for sections within sections.
\subsection{Subsection}
I can put a subsection inside my first section.
\section{Lists}
There are two types of lists: ordered and unordered.
\subsection{Ordered}
Ordered lists have a number or letter associated with each item.
\begin{enumerate}
\item Item 1
\item Item 2
\item Item 3
\end{enumerate}
\end{document}
When you compile this document, you should see something like this in the preview pane:
Callout
Note that the \item
commands do not need to be enclosed
in braces. These commands do not take any arguments, so they can be used
as standalone commands. The text that follows the \item
command will be treated as the content of the list item. However, you
are able to specify your own bullet point symbols with
\item[]
manually. For instance, if you want a list with
small letters in brackets you can use the following LaTeX code:
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
% List with custom bullet point symbols
\begin{itemize}
\item[(a)] Item 1
\item[(b)] Item 2
\item[(c)] Item 3
\end{itemize}
\end{document}
Adding an unordered list is just as easy. We can use the exact same
syntax, but replace the enumerate
environment with
itemize
.
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
Hello World!
This is my first LaTeX document.
% The section command automatically numbers and formats the section heading.
\section{Sections}
I can add content to my first section!
% The subsection command does the same thing, but for sections within sections.
\subsection{Subsection}
I can put a subsection inside my first section.
\section{Lists}
There are two types of lists: ordered and unordered.
\subsection{Ordered}
Ordered lists do not have numbers or letters associated with each item.
\begin{enumerate}
\item Item 1
\item Item 2
\item Item 3
\end{enumerate}
\subsection{Unordered}
Unordered lists are just a series of items preceded by a marker.
\begin{itemize}
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\end{document}
Challenges
Challenge 1: What needs to change?
Challenge 2: Can you do it?
We would like to have the following appear in our LaTeX document:
- Apples
- Gala
- Fuji
- Granny Smith
- Bananas
- Oranges
How would you write this in LaTeX?
Challenge 3: Enumerate your list manually
We would like to have the following appear in our LaTeX document:
- Gala
- Fuji
- Granny Smith
How would you write this in LaTeX without using
enumerate
but itemize
with
\item[]
?
Key Points
- LaTeX documents are structured using section commands.
- There are many different section commands in LaTeX, including
\subsubsection{...}
,\paragraph{...}
,\chapter{...}
, and more. - Lists in LaTeX are created using the
enumerate
anditemize
environments.
After this episode, here is what our LaTeX document looks like.
Content from Using Document Classes
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- What is a LaTeX Document class?
- How does a document class affect the layout of a LaTeX document?
Objectives
- Identify the various types of document classes available in LaTeX
- Create a document using an alternative document class
What is a Document Class?
A document class sets up the general layout of the document, including (but not limited to):
- design (margins, fonts, spacing, etc)
- availability of chapters
- title page layout
Document classes can also add new commands and environments to the document.
The Base Document Classes
LaTeX comes with a set of standard document classes:
-
article
: a short document without chapters -
report
: a longer document with chapters, intended for single sided printing -
book
: a longer document with chapters, intended for double sided printing, as well as other features like front and back matter -
letter
: a short document with no sections -
slides
: a document for creating slide presentations
We’re going to leave our main.tex
file for a minute and
play around with some of these document classes.
Writing a Letter
So far we’ve been using the article
document class.
Let’s try using the letter
document class to write a
letter.
Callout
We’ve been working in “main.tex” so far, but we can create as many files in this project as we want. Let’s create a new file called “letter.tex” and write our letter there.
LATEX
\documentclass{letter}
\begin{document}
\begin{letter}{Some Address\\Some Street\\Some City}
\opening{Dear Sir or Madam,}
The text goes Here
\closing{Yours,}
\end{letter}
\end{document}
Callout
Note the \\
used to create line breaks in the address -
we’ll get back to line breaking in a bit.
Creating a Presentation
The slides
document class was developed for making
physical slides in the mid-1980s, and so doesn’t have any of the
features we might use in modern presentations. Let’s create a simple
presentation using the slides
document class. Start another
new document called “slides.tex”.
LATEX
\documentclass{slides}
\begin{document}
\begin{slide}
The slides document class is a good starting point for creating a presentation.
\end{slide}
\begin{slide}
Being entirely text-based, it's not as powerful or user-friendly as modern presentation software.
\end{slide}
\end{document}
When you compile this document, you should end up with a document that has two pages, each with the text of each slide centered in the middle of the page.
Function-rich Classes
The core classes included with base LaTeX are very stable, but this means they are also somewhat conservative in terms of features. Over time, third parties have developed a number of more powerful classes that add new features and functionality to LaTeX documents.
These include:
-
amsbook
,amsart
, andamsproc
: classes for documents that use the American Mathematical Society’s style -
beamer
: a class for creating slide presentations -
KOMA-Script
: a set of classes that provide a more modern look and feel to LaTeX documents by providing parallel classes to the base classes -
memoir
: a class that provides a lot of functionality for creating books, reports, and articles
These classes have a lot of customization options that can be used to alter the appearance of the document to exactly match your needs. We’ll explore how to figure out how to use these classes in a later episode.
Challenges
Challenge 1: Which don’t belong?
Which of the following are not a standard LaTeX document class?
article
report
book
letter
presentation
memoir
presentation
is not a standard LaTeX document class -
the correct class is slides
. Also memoir
is
not a standard LaTeX document class, but a third-party class.
Challenge 2: What happens?
Suppose we have the following LaTeX slide presentation, but we want to turn it into an article. We can change the document class from “slides” to “article”, but what happens? And why?
LATEX
\documentclass{slides}
\begin{document}
\begin{slide}
Apples are an edible fruit produced by an apple tree. The tree originated in Central Asia, but
has since been introduced to many other regions.
\end{slide}
\begin{slide}
Some popular apple varieties include:
\begin{itemize}
\item Gala
\item Fuji
\item Golden Delicious
\end{itemize}
\end{slide}
\end{document}
We can change the document class from “slides” to “article”, but the
slide
environment does not exist in the
article
document class. We end up with errors when we try
to compile the document, complaining that the slide
environment is not defined. We need to change the slide
environments to sections
or subsections
to
maintain the structure of the document:
LATEX
\documentclass{article}
\begin{document}
\section{Apples}
Apples are an edible fruit produced by an apple tree. The tree originated in Central Asia, but
has since been introduced to many other regions.
\subsection{Popular Apple Varieties}
Some popular apple varieties include:
\begin{itemize}
\item Gala
\item Fuji
\item Golden Delicious
\end{itemize}
\end{document}
Challenge 3: Make your own beamer slides
Consider the following minimal example of an initial
beamer
presentation. Let’s create a new file called
“beamer.tex” and copy the following code as a template into it:
LATEX
\documentclass{beamer}
%Information to be included in the title page:
\title{Sample title}
\author{Anonymous}
\institute{Overleaf}
\date{2021}
\begin{document}
\frame{\titlepage}
\begin{frame}
\frametitle{Sample frame title}
This is some text in the first frame. This is some text in the first frame. This is some text in
the first frame.
\end{frame}
\end{document}
Adapt these slides in the following way:
- Change the title to “LaTeX Workshop”
- Change the name of the author to your name.
- Change the institution name to “ABCD Project Group”.
- Change the date to “2025”.
- Change the frame title of the first slide after the title page to “What I have learned in this episode” and replace the example text on the slide with your key takeaway from this section.
- Besides the title page and the slide after the title page, create a third slide with the title “What I learned in the previous episodes”.
- Add an unordered list as content to this slide and describe in three bullet points your key takeaways from the previous episodes.
LATEX
\documentclass{beamer}
%Information to be included in the title page:
\title{LaTeX Workshop}
\author{My Name}
\institute{ABCD Project Group}
\date{2025}
\begin{document}
\frame{\titlepage}
\begin{frame}
\frametitle{What I have learned in this episode}
My key takeaway from this episode.
\end{frame}
\begin{frame}
\frametitle{What I learned in the previous episodes}
\begin{itemize}
\item Key learning 1
\item Key learning 2
\item Key learning 3
\end{itemize}
\end{frame}
\end{document}
Key Points
- LaTeX document classes set the general layout of the document
- The base document classes are
article
,report
,book
,letter
, andslides
- Third-party classes can provide additional features
After this episode, here is what our LaTeX document looks like.
Content from Extending LaTeX
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How can I extend LaTeX to suit my needs?
- How can I define my own commands in LaTeX?
Objectives
- Demonstrate how to extend LaTeX using packages.
- Add custom commands to a LaTeX document.
Adding Packages
After we’ve declared a class, we can use the preamble section of our document to add one or more packages in order to extend LaTeX’s functionality. Packages are collections of commands and environments that add new features to LaTeX, for example:
- Changing how some parts of LaTeX work.
- Adding new commands.
- Changing the appearance/design of the document.
We can add a package to our document by using the
\usepackage
command in the preamble of our document. For
example, to add the geometry
package to our document, we
would add the following line to the preamble:
In addition to the name of the package in the curly braces, we can also add options to the package by adding them in square brackets before the package name. For example, to set the width of the text block in our document to 6cm, we would update this line to look like this:
Give this a try in our main.tex
document to see what
happens. When you render the document, you should see something like
this:
However this isn’t what we really want, so we’ll remove this line from our document.
Changing the Design
It’s useful to be able to adjust some aspects of the design
independent of the document class, for example, the page margins. We
used the geometry
package in our previous example to set
the width of the text block, but now let’s use it to specifically set
the margins of our document:
Callout
So far we’ve been showing the entire document in the examples. Going
forward, we’ll only show the relevant sections of the document that
we’re discussing, so keep in mind when we are talking about “adding this
to the preamble” we mean adding it to the section of the document
before the \begin{document}
command.
Let’s add this to the preamble of our document:
You should see that adding this package and setting the “margin”
option to 1in
has shrunk the margins of the document (try
commenting out the \usepackage
line with a %
and recompiling to see the difference).
Defining Custom Commands
Using other people’s packages is great, but what if there is some
kind of functionality we want to add to our document that isn’t covered
by a package? Or some specific formatting we want to use repeatedly? We
can define our own commands in LaTeX using the \newcommand
command.
The \newcommand
syntax looks like this:
Callout
We could be even more flexible by using an optional argument
in our \newcommand
. Then the general structure of the
command looks like this
LATEX
\newcommand{\commandname}[number of arguments][default value for the first argument]{definition}
You can learn more about optional arguments in the last challenge of this episode.
As an example, let’s define a command that will highlight specific
works in a document, so that they appear italicised and underlined. We
could do this by writing \textbf{\underline{word}}
around each word we want to highlight:
LATEX
This is my first \textbf{\underline{LaTeX}} document.
\section{Sections}
I can add content to my first \textbf{\underline{section}}!
We can add this to each of our important terms in our document - maybe it looks something like this:
In a long document this would quickly become tedious. Instead, let’s
define a new command called \kw
in the preamble of our
document that will do this for us:
LATEX
% The \newcommand defines a new custom command
% Highlight Keywords using the \kw{} command
\newcommand{\kw}[1]{\textbf{\underline{#1}}}
Now we can use the \kw
command to highlight words in our
document:
LATEX
This is my first \kw{LaTeX} document.
\section{Sections}
I can add content to my first \kw{section}!
Callout
Let’s take a minute to go through and add the \kw
command to all the keywords in our document.
- LaTeX
- section
- subsection
- lists
- ordered
- unordered
Related to the \newcommand
command, we can also use the
\renewcommand
command to change the definition of an
existing command. This is useful, for example, if we want to change the
effect of a command partway through a document, or if we want to change
the definition of a command that is already defined in a package. It has
an identical syntax to the \newcommand
command:
Code Reuse
This also means that we can easily change the formatting of all the
words we’ve highlighted by updating the definition of the
\kw
command. Let’s say we wanted to change the formatting
to bold and change the color to blue:
Let’s replace our \kw
command with this new definition:
\newcommand{\kw}[1]{\textcolor{blue}{\textbf{#1}}}
When we recompile the document we should see that the formatting of our keywords has changed all at once:
Defining Multiple Commands
We can define as many commands as we like in the preamble of our document. Let’s add another one that we can use to highlight commands in the document:
We’ll use this command in later sections.
Challenges
Challenge 1: Importing a new package
A useful package to preview what your document will look like before
your write a lot of text is the lipsum
package. This
package provides sample text blocks from a common placeholder text.
How would you add the lipsum package to the preamble of your document?
Add the line \usepackage{lipsum}
to the preamble of your
document.
You can then use the \lipsum
command in the body of your
document to add some dummy text.
Challenge 2: What does this mean?
The definition of a new command in LaTeX is done with the
\newcommand
command. The syntax for this command is:
So if we modify the \kw
command we defined above to look
like this:
What would the new \kw
command do? and how would we use
it?
Challenge 3: Can you write your own command with two arguments?
Suppose you want to define a new command that takes as input two words as arguments. This first word shall be written bold while the second word shall be written italic. Moreover, the first and the second word are separated by a comma followed by a whitespace.
Use \newcommand
to define this command that takes two
arguments as inputs and name it \bo_it
. Write the following
sentence into your LaTeX document using your new command
\bo_it
:
This newly defined command highlights these two words: Apple, Banana.
The new \boit
command would take two arguments: the
first argument would be used with \tetxbf{#1}
to make the
first word appear bold, and the second argument would
be used with \tetxit{#2}
to make the first word appear
italic. Between \tetxbf{#1}
and
\tetxit{#2}
, we would write ,
to separate both
words. We would use the new command like this:
Challenge 4: Optional arguments
New commands can be made even more flexible by defining commands that take an optional argument. Then the general LaTeX code for this looks like this:
LATEX
\newcommand{\commandname}[number of arguments][default value for the first argument]{definition}
The optional argument can be accessed and changed by writing square
brackets []
directly after the \commandname
in
the body of your document.
Consider the following, modified example of our \kw
from
before where we now use an optional argument.
In your LaTeX file, use the new \kw
command to write
down the words “Banana” in yellow, “Apple” in red, and “Blueberry” in
blue. Each word should be written in a separate line.
We can exploit the optional argument in \kw
to write
down the given words very efficiently. For the first word, we change the
optional argument to “yellow”. For the second word, we stick with the
default value of “red”. For the third word, we change the optional
argument to “blue”.
Key Points
- We can extend LaTeX’s functionality by adding packages to our document.
- We can define custom commands in LaTeX using the
\newcommand
command.
After this episode, here is what our LaTeX document looks like.
Content from Using Graphics
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do I include images in a LaTeX document?
Objectives
- Demonstrate how to include images in a LaTeX document.
- Show how to position images manually / automatically in a LaTeX document.
The Graphicx Package
In order to use graphics in our document, we’ll need to use the
graphicx
package, which adds the
\includegraphics
command to LaTeX. We’ll add this to the
preamble of our document:
We can now include several types of images in our document, including:
- JPEG
- PNG
- EPS
For the purposes of this lesson, we’ll use the following image:

Callout
Download this image to your computer either be right-clicking on the image and selecting “Save Image As…” or by clicking on the image and saving it from the browser.
You can use any image you like for this lesson. Just make sure to
replace example-image.PNG
with the name of your image in
the following examples.
Uploading Images to Overleaf
In order to incorporate an image into our document, we’ll need to upload it to Overleaf. We can do this by clicking on the “Upload” icon on the upper left corner of the Overleaf editor:
We can then either drag and drop the image into the upload window or click on the “Select files” button to choose the image from our computer.
Once you have uploaded the image, you should see it in the “Files” section of the Overleaf editor:
You can also use the “From external URL” option to add an image directly from a URL, which would let you use an image from a website directly without having to download it first.
Including an Image in a LaTeX Document
Now that we have our image uploaded, we can include it in our
document using the \includegraphics
command:
LATEX
\section{Graphics}
We can include \kw{images} in our document using the \cmd{graphicx} package, which lets us use the
\cmd{includegraphics} command.
\includegraphics{example-image.PNG}
Your document should now look like this:
Callout
If you just want to see how an image might look in your document
without having to upload one, you can use the filepath
example-image
in the \includegraphics
command.
This will display a placeholder image in your document that you can
replace later.
Adjusting the appearance of the image
But wait! The image is too big, and it doesn’t fit on the page, so LaTeX has moved it to the next page. Since the image is a little too large to fit on the same page as the text, LaTeX has moved it automatically to the next page. Let’s address that by making the image smaller.
We can adjust the appearance of the image by passing options to the
\includegraphics
command, just like we did earlier with the
geometry
package. For example, we can specify the height of
the image:
LATEX
\subsection{Small Image}
We can pass parameters to the \cmd{includegraphics} command to adjust the appearance of the image.
\includegraphics[height=2cm]{example-image.PNG}
Other possible options include:
\begin{itemize}
\item width: the width of the image
\item scale: the scaling factor of the image
\item angle: the angle of rotation of the image
\item clip: whether to clip the image to its bounding box
\item trim: trim the image by a specified amount
\item draft: display a box instead of the image
\end{itemize}
Callout
Some other possible options from the graphicx
package
include:
-
width
: the width of the image -
scale
: the scaling factor of the image -
angle
: the angle of rotation of the image -
clip
: whether to clip the image to its bounding box -
trim
: trim the image by a specified amount -
draft
: display a box instead of the image
Positioning the image
We can place the image inside of an environment to help position it
in the document. Let’s try placing the \includegraphics
command inside of a \begin{center}
and
\end{center}
environment:
LATEX
\subsection{Centered Image}
By placing the \cmd{includegraphics} command inside a center environment, we can center the
image on the page.
\begin{center}
\includegraphics[height=2cm]{example-image.PNG}
\end{center}
You should see that the image is now centered on the page:
“Floating” Images
It’s often the case that images need to “float” around the document as new text is added or removed. this is called a “floating” image. Images are normally included as floats so that we don’t end up with large gaps in the document.
To make an image float, we can use the figure
environment:
LATEX
\subsection{Floating Image}
\kw{Floating images} can move around the page as text is added or removed. We can use the
\cmd{figure}environment to create a floating image.
\begin{figure}
\centering
\includegraphics[height=2cm]{example-image.PNG}
\end{figure}
When we render the document, we can see that, even though we placed the image at the end of the document, it appears at the top of the page:
Callout
You might have noticed that instead of using the
\begin{center}
and \end{center}
environment,
we used the \centering
command inside of the
figure
environment. This is because the figure
environment is a floating environment, and the \centering
command is the recommended way to center content inside of a floating
environment.
Controlling the Position of a Floating Image
We can pass parameters to the figure
environment to
control the position of the floating image:
-
h
: Place the float “here” (where it appears in the code) -
t
: Place the float at the “top” of the page -
b
: Place the float at the “bottom” of the page -
p
: Place the float on a “page” by itself
It is also possible to combine these options. For example, to place
the float here if possible, but otherwise at the top of the page, we can
use the ht
option. Let’s update our figure
environment to use the ht
option:
LATEX
\begin{figure}[ht]
\centering
\includegraphics[height=2cm]{example-image.PNG}
\end{figure}
Control the position of a floating image by passing parameters to the \cmd{figure} environment:
\begin{itemize}
\item h: Place the float "here" (where it appears in the code)
\item t: Place the float at the "top" of the page
\item b: Place the float at the "bottom" of the page
\item p: Place the float on a "page" by itself
\end{itemize}
Callout
You can use the package wrapfig
together with
graphicx
in your preamble. This makes the
wrapfigure
environment available and we can place an
\includegraphics
command inside it to create a figure
around which text will be wrapped. Here is how we can specify a
wrapfigure
environment:
We will describe the wrapfigure
environment in more
detail in one of the challenges below.
Adding a Caption
We can add a caption to our image by using the \caption
command inside of the figure
environment:
LATEX
\subsection{Caption}
We can add a \kw{caption} to our floating image by using the \cmd{caption} command inside of the
\cmd{figure} environment.
\begin{figure}
\centering
\includegraphics[height=2cm]{example-image.PNG}
\caption{This is a caption for our image.}
\end{figure}
When we render the document, we can see that the caption appears below the image:
Callout
Note that the caption is automatically numbered “Figure 1”. Very handy! We’ll see how we can automatically reference figures and tables in a later episode.
Another package that we can use to work with images in LaTeX is the
hvfloat
package. This package is an alterantive way of
controlling the position of floating elemnents in LaTeX, like images and
tables. It provides a more flexible way of positioning floats allowing
us to, for example, place a float at the bottom of the page, even if
there is not enough space for it to fit.
Challenges
Challenge 1: Can you do it?
Consider again our running example of example-image.PNG
.
Include this image into your LaTeX document by using the
figure
environment. Make sure that your image is centered
and rotate the image by 45 degree. Add the following caption to your
image: “This caption has a bold word included.” How
would your LaTeX look like?
We use the \centering
command in the figure
environment and specify angle=45
to rotate the image.
Challenge 2: What is wrong here?
Have a look at the following LaTeX code:
LATEX
\documentclass{article}
\begin{document}
\centering
\begin{figure}
\includegraphics[height=3cm, draft]{example-image.PNG}
\caption{This caption has a \textbf{bold} word included.}
\end{figure}
\end{document}
Can you spot all the errors in this LaTeX code? Change the code such that the image is displayed with a height of 3cm, width of 4cm and centered.
First, the command \usepackage{graphicx}
is missing in
the preamble. Second, the \centering
command has to be
placed into the figure
environment. Third, the
draft
argument has to be removed from and
width=4cm
added to the \includegraphics
command.
The corrected LaTeX code looks like this:
Challenge 3: Making a command for images
In the previous section, we created a command to highlight keywords
in our document. Let’s create a new command to make it easier to include
images in our document. We’ll create a command called
\centeredimage
that takes two arguments: the image filename
and the caption. The resulting image should be centered on the page and
have a caption below it. Use the example-image.png from earlier in this
episode.
Your file should look like this:
LATEX
\documentclass{article}
\usepackage{graphicx}
% Define our new command
%%% YOUR COMMAND HERE %%%
\begin{document}
\centeredimage{example-image.png}{"My Image"}
\centeredimage{example-image.png}{"My Other Image"}
\end{document}
And your output should look like this.
Reminder: The syntax for creating a new command is:
LATEX
\documentclass{article}
\usepackage{graphicx}
% Define our new command
\newcommand{\centeredimage}[2]{
\begin{figure}
\centering
\includegraphics{#1}
\caption{#2}
\end{figure}
}
\begin{document}
\centeredimage{example-image.png}{"My Image"}
\centeredimage{example-image.png}{"My Other Image"}
\end{document}
Challenge 4: The wrapfig
package.
Have a look at the following LaTeX code that uses the
wrapfigure
environment. Can you already guess how the
images will be displayed in your document?
LATEX
\documentclass{article}
\usepackage{wrapfig}
\usepackage{graphicx}
\begin{document}
\begin{wrapfigure}{r}{0.1\textwidth}
\centering
\includegraphics[width=0.1\textwidth, height=0.1\textwidth]{example-image.PNG}
\end{wrapfigure}
The package wrapfigure lets you position images around your text.
That comes in handy if you want to integrate images seamlessly into your written sentences.
Therefore, I add a few more sentences here to showcase this integration to you.
\begin{wrapfigure}{l}{0.1\textwidth}
\centering
\includegraphics[width=0.1\textwidth, height=0.1\textwidth]{example-image.PNG}
\end{wrapfigure}
Be careful, you need both packages, wrapfig and graphicx, in your preamble to display your images
and wrap them accordingly. There are several ways to display images, depending on the arguments you
specify. For instance, you can scale the image width according to the width of the text.
\end{document}
The first image will be placed at the right of the following
paragraph of text as {r}
is specified as an argument within
the first wrapfigure
environment. The second image will be
placed at the left of its following paragraph of text as
{l}
is specified as an argument within the second
wrapfigure
environment. Moreover, both images are scaled by
being 0.1 of the width of the text in your document.
Key Points
- The
graphicx
package allows us to include images in our LaTeX document. - We can adjust the appearance of images using options in the
\includegraphics
command. - We can position images manually or automatically using environments
like
center
andfigure
. - Floating images can move around the page as text is added or removed.
- We can control the position of floating images using parameters in
the
figure
environment. - We can add captions to floating images using the
\caption
command.
After this episode, here is what our LaTeX document looks like.
Content from Tables
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do I add tables to a LaTeX document?
- How can I format a table in a LaTeX document?
Objectives
- Create a table in a LaTeX document.
- Customize the appearance of a table in a LaTeX document.
- Add horizontal lines to a table in a LaTeX document.
Defining Tables
Tables in LaTeX are set using the tabular
environment.
For our purposes here, we are going to use the array
package to create a table, which provides additional functionality for
creating tables. We’ll add this to the preamble of our document:
Callout
As we start to add more and more packages to our preamble, it can get a bit unwieldy. For now, let’s just keep them alphabetized to make it keep things organized. Our imports should now look like this:
In order to create a table, we need to tell latex how many columns we will need and how they should be aligned.
Available column types are:
Column Type | Description |
---|---|
l |
left-aligned |
c |
centered |
r |
right-aligned |
p{width} |
a column with fixed width; the text will be automatically line wrapped and fully justified |
m{width} |
like p, but vertically centered compared to the rest of the row |
b{width} |
like p, but bottom aligned |
w{align}{width} |
prints the contents with a fixed width, silently overprinting if things get larger. (You can choose the horizontal alignment using l, c, or r.) |
W{align}{width} |
like w, but this will issue an overfull box warning if things get too wide. |
Callout
The columns l, c and r will have the natural width of the widest
entry in the column. Each column must be declared, so if you want a
table with three centered columns, you would use ccc
as the
column declaration.
Creating a Table
Now that we have the array package loaded and we know how to define
columns, we can create a table using the tabular
environment.
Callout
Note that the &
and \\
characters are
aligned in our example. This isn’t strictly necessary in LaTeX, but it
makes the code much easier to read.
LATEX
\section{Tables}
\kw{Tables} are defined using the \cmd{tabular} environment.
\begin{tabular}{lll}
Fruit & Quantity & Price \\
Apple & 5 & 1.50 \\
Banana & 6 & 2.00 \\
Orange & 4 & 1.20 \\
\end{tabular}
This will create a table with three columns, all left-aligned. The
values of each row are separated by &
and the rows are
separated by \\
. We do not yet have any horizontal lines in
the table, so it will look like this:
Callout
If your table has many columns, it may get cumbersome to write out
the column definitions every time. In this case you can make things
easier by using *{num}{string}
to repeat the string
num
times. For example, in our table above, we can instead
write:
Adding Horizontal Lines
We’re going to introduce another package here: booktabs
.
This package provides a few commands that make it easier to create
professional looking tables. To use it, add the following to your
preamble:
booktabs
provides three commands for creating horizontal
lines in your table:
-
\toprule
: creates a line at the top of the table -
\midrule
: creates a line in the middle of the table -
\bottomrule
: creates a line at the bottom of the table
Horizontal lines make tables easier to read and understand, and they can be used to separate the header from the body of the table, and the body from the footer. We can insert these commands into our table to add horizontal lines:
LATEX
\subsection{Tables with Horizontal Lines}
We can use the \cmd{\textbackslash toprule}, \cmd{\textbackslash midrule}, and
\cmd{\textbackslash bottomrule} commands from the \cmd{booktabs} package to create horizontal
lines in our table.
\begin{tabular}{*{3}{l}}
\toprule
Fruit & Quantity & Price \\
\midrule
Apple & 5 & 1.50 \\
Banana & 6 & 2.00 \\
Orange & 4 & 1.20 \\
\bottomrule
\end{tabular}
Your table should look something like this:
Callout
A general recommendation is to use lines sparsely in your tables, and vertical lines should be avoided.
Partial Horizontal Lines
Another useful feature of booktabs
is the ability to
create partial horizontal lines with the \cmidrule
command.
This command accepts the arguments {number-number}, where the first
number is the column to start the line and the second number is the
column to end the line.
LATEX
\subsection{Partial Horizontal Lines}
The \cmd{\textbackslash cmidrule} command can be used to create partial horizontal lines in a
table. The command accepts the arguments {number-number}, where the first number is the column to
start the line and last number is the column to end the line.
\begin{tabular}{*{3}{l}}
\toprule
Fruit & Quantity & Price \\
\midrule
Apple & 5 & 1.50 \\
Banana & 6 & 2.00 \\
Orange & 4 & 1.20 \\
\cmidrule{3-3}
Total & 15 & 28.20 \\
\bottomrule
\end{tabular}
This table should come out looking something like this:
Merging Cells
We can merge cells horizontally using the \multicolumn
command. This command takes three arguments:
- The number of cells which should be merged
- The alignment of the merged cell (l, c, or r)
- The contents of the merged cell
LATEX
\subsection{Merging Cells}
Merge cells horizontally using the \cmd{\textbackslash multicolumn} command. This command takes
three arguments:
\begin{itemize}
\item The number of cells which should be merged
\item The alignment of the merged cell (l, c, or r)
\item The contents of the merged cell
\end{itemize}
\begin{tabular}{*{3}{l}}
\toprule
\multicolumn{3}{c}{Overall Inventory} \\
Fruit & Quantity & Price \\
\midrule
Apple & 5 & 1.50 \\
Banana & 6 & 2.00 \\
Orange & 4 & 1.20 \\
\midrule
\multicolumn{2}{c}{Summary} \\
Total & 15 & 28.20 \\
\bottomrule
\end{tabular}
Callout
Vertical merging is supported in LaTeX by using the
multirow
package which has the \multirow
command equipped with it. It is similarly structured as
\multicolumn
by using three arguments:
- The number of rows which should be merged
- The width of the column (i.e. 4em)
- The contents of the merged rows.
You can find an example in the challenges below.
This will create a table that looks like this:
Challenges
Challenge 1: Can you do it?
Try to replicate the following table in LaTeX:
Make | Model | Sold |
---|---|---|
Volkswagen | Golf | 7,687 |
Skoda | Octavia | 4,078 |
Seat | Leon | 3,922 |
Volkswagen | Passat | 3,776 |
Mercedes | GLK,GLC | 3,143 |
Total | 22,606 |
Your LaTaX version should look something like this.
Note that the last row is a bit different from the others. The first two columns re merged, the text “Total” is right-aligned and bold, and the value in the last column is italicized.
(Data for this challenge is from Statista)
LATEX
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\begin{document}
\begin{tabular}{lll}
\toprule
Make & Model & Sold \\
\midrule
Volkswagen & Golf & 7,687 \\
Skoda & Octavia & 4,078 \\
Seat & Leon & 3,922 \\
Volkswagen & Passat & 3,776 \\
Mercedes & GLK,GLC & 3,143 \\
\midrule
\multicolumn{2}{r}{\textbf{Total}} & \textit{22,606} \\
\bottomrule
\end{tabular}
\end{document}
Challenge 2: Merging rows.
Consider the following LaTeX code that creates a table using the
command \multirow
. Can you guess how this table will look
like? How many columns will it have? How many rows? Are any rows or
columns combined?
LATEX
\documentclass{article}
\usepackage{booktabs}
\usepackage{multirow}
\begin{document}
\begin{tabular}{*{4}{l}}
\toprule
& Food & Quantity & Price \\
\midrule
\multirow{3}{4em}{Fruit} & Apple & 5 & 1.50 \\
& Banana & 6 & 2.00 \\
& Orange & 4 & 1.20 \\
\midrule
\multirow{2}{4em}{Cheese} & Brie & 2 & 3.30 \\
& Asiago & 3 & 2.90 \\
\bottomrule
\end{tabular}
\end{document}
The table will have 4 columns where the first column does not have a column name. The table will have 6 rows. The first row is the column name row. Rows 2 to 4 are merged for “Fruit”. Rows 5 and 6 are merged for “Cheese”.
Hint: We want to make sure the caption stays with the table, so we should put the table inside an environment. For images we use the “figure” environment, but for tables we can use the “table” environment.
Challenge 3: Adding merged rows to your table.
Consider again the LaTeX code for the table in challenge 3. Add four more rows to this table that contain information about the following four sorts of bread:
- Brioche, 3, 3.00
- Bagel, 2, 3.50
- Matzah, 4, 3.60
- Naan, 2, 3.40
Use \multirow
to subsume those bread types under the
category “Bread”.
LATEX
\documentclass{article}
\usepackage{booktabs}
\usepackage{multirow}
\begin{document}
\begin{tabular}{*{4}{l}}
\toprule
& Food & Quantity & Price \\
\midrule
\multirow{3}{4em}{Fruit} & Apple & 5 & 1.50 \\
& Banana & 6 & 2.00 \\
& Orange & 4 & 1.20 \\
\midrule
\multirow{2}{4em}{Cheese} & Brie & 2 & 3.30 \\
& Asiago & 3 & 2.90 \\
\midrule
\multirow{4}{4em}{Bread} & Brioche & 3 & 3.00 \\
& Bagel & 2 & 3.50 \\
& Matzah & 4 & 3.60 \\
& Naan & 2 & 3.40 \\
\bottomrule
\end{tabular}
\end{document}
Challenge 4: Making the Table Colorful
We used the xcolor
package to add color to our text in
an earlier episode. Can you use the xcolor
package to make
the header and summary rows of the table in Challenge 1 a different
color? What about changing the color of the text in the summary row? Can
we make the rows of the table alternate colors?
A few things that will help you: - We need to import the
xcolor
package in the preamble of our document. - The
xcolor
package doesn’t automatically support coloring
tables, so we need to add the table
option to the package
import. - \rowcolor{(<color>}
-
\rowcolors{<starting row number>}{<color1>}{<color2>}
- You can make lighter versions of colors by adding
!<percentage>
to the color name. For example,
red!10
is a light red color, while red!90
is a
darker red color.
There’s no right answer to this challenge, so feel free to experiment with different colors! Here’s an example of what you can do.
LATEX
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\usepackage[table]{xcolor} % Import xcolor with the table option
\begin{document}
\begin{table}[ht]
\centering
\rowcolors{2}{red!10}{gray!10} % Alternate row colors between red and gray
\begin{tabular}{lll}
\toprule
\rowcolor{green!20} % Set the header row color to green
Make & Model & Sold \\
\midrule
Volkswagen & Golf & 7,687 \\
Skoda & Octavia & 4,078 \\
Seat & Leon & 3,922 \\
Volkswagen & Passat & 3,776 \\
Mercedes & GLK,GLC & 3,143 \\
\midrule
\rowcolor{blue!20} % Set the summary row color to blue
\multicolumn{2}{r}{
% Set the text color to blue and bold for the summary row
\textbf{\textcolor{blue!75}{Total}}} & \textit{\textcolor{blue!75}{22,606}} \\
\bottomrule
\end{tabular}
\caption{Car Sales by Make/Model (January 2025)} % Add a caption to the table
\end{table}
\end{document}
Key Points
- Tables in LaTeX are created using the
tabular
environment. - The
array
package provides additional functionality for creating tables. - The
booktabs
package provides commands for creating horizontal lines in tables. - The
\multicolumn
command can be used to merge cells in a table. - The
\multirow
command in themultirow
package can be used to merge rows in a table.
After this episode, here is what our LaTeX document looks like.
Content from Adding Cross References
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How can I ensure that numbers in my document are automatically updated?
- How can I refer to numbered elements in my document?
Objectives
- Insert a cross-reference in a LaTeX document.
- Refer to a cross-referenced element in a LaTeX document.
Cross References
When writing a document of any length, you’ll often want to refer to numbered elements such as figures, tables, equations, or sections. LaTeX provides a way to automatically number these elements and refer to them in your text.
Label and Ref
To have LaTex remember a specific spot in your document, you have to
use the \label{}
command to mark it, and the
\ref{}
command to refer to it. For example:
LATEX
\section{Cross References}
\label{sec:cross-references}
\subsection{Material for the Introduction}
In this section, we introduce two new concepts:
\begin{tabular}{cp{9cm}}
Command & Description \\
\toprule
\kw{label} & Marks a spot in the document \\
\kw{ref} & Refers to a marked spot in the document \\
\bottomrule
\label{tab:cross-reference-commands}
\end{tabular}
We can \kw{refer} to the section with the \cmd{ref} command, like this: \ref{sec:cross-references}.
We can likewise refer to the table like this: \ref{tab:cross-reference-commands}.
Callout
The sec
and tab
prefixes in the
\label{}
command are not required, but they help to
identify the type of element being labeled. This is especially useful
when you have many labels in your document.
The label command always refers to the previous numbered entry: a
section, a table, a figure, etc. This means that the
\label{}
command should always come after the
numbered element you want to refer to.
Callout
Note that the ref
command does not insert the section or
table name, but rather the number associated with it. We would still
write “Refer to Table \(\ref{tab:cross-reference-commands}\)”, but
the benefit is that if the table number changes because we’ve added or
removed sections before it, the reference will update automatically.
There are packages that can provide more advanced cross-referencing
capabilities, such as the cleveref
package, which can
automatically detect the type of element being referenced and insert the
appropriate name. For more details about this, refer to the references
section.
Challenges
Challenge 1: Add a figure, then reference it.
In your LaTeX document, include the image
example-image.PNG
and cross-reference it in the text. Make
sure the figure has a caption and is labeled and centered properly. Use
the \includegraphics
command to add the image and wrap it
in a figure
environment. Then, refer to it in the text
using the \ref
command.
You may find the following LaTeX template helpful.
As shown in \(\ref{tab:findings}\) post-treatment values are higher…
LATEX
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\section{Cross-referencing Figures}
Here is an example of a figure in the document. We will refer to it later in the text.
\begin{figure}[ht]
\centering
\includegraphics[height=4cm]{example-image.PNG}
\caption{This is an example figure.}
\label{fig:example-image}
\end{figure}
In the text, we can refer to the figure using its label: Figure \ref{fig:example-image}.
\end{document}
Challenge 2: Where does the reference go?
We mentioned that the \label{}
command should always
come after the numbered element you want to refer to. What do you think
would happen if we put the \label{}
command before the
numbered element? For example:
LATEX
\documentclass{article}
\usepackage{lipsum}
\begin{document}
\section{Introduction}
\label{sec:intro}
\lipsum[1]
\label{sec:methods}
\section{Methodology}
\lipsum[2]
\section{Findings}
As indicated in Section \ref{sec:methods}, \lipsum[3][2]
\end{document}
The \lipsum
package is a nice way of quickly
generating large amounts of placeholder text - great if you just want to
get an idea of how your document will look!
Before you run the code, think about what will happen. What do you expect the output to be? Run the code and see if your expectations were correct. Why or why not?
You might have expected the output to be either “As indicated in
Section 2, …” or “As indicated in Section ???”, but it actually returns
“As indicated in Section 1, …”. This is because the
\label{}
command marks the section number
immediately preceding it. In this case, the
\label{}
command is placed before the
\section{Methodology}
command, so it marks the section
number of the previous section, which is the Introduction
section. The fact that the Introduction
section already has
a label does not matter.
Challenge 3: What’s wrong with this code?
Here’s a section from a larger document. Why might the references not be working as expected? (This is a tiny but common issue!)
LATEX
\section{Findings}
\label{sec:findings}
\begin{table}[ht]
\centering
\begin{tabular}{lll}
\toprule
Color & Pre-treatment & Post-treatment \\
\midrule
Blue & 30\% & 35\% \\
Green & 15\% & 55\% \\
Red & 10\% & 12\% \\
\bottomrule
\end{tabular}
\caption{Findings from the survey.}
\label{tab:findings}
\end{table}
As shown in \ref{tab:findings} post-treatment values are higher...
The document compiles without error, but the reference text has an issue. What is it? Why does this happen?
The \ref{}
command is correctly written, but the
\ref{}
command only returns the number of the label it is
referring to. In this case, it will return the number of the table, not
the name of the table. To fix this, you can write “As shown in Table
\(\ref{tab:findings}\)…”
Key Points
- The
\label{}
command marks a spot in the document. - The
\ref{}
command refers to a marked spot in the document.
After this episode, here is what our LaTeX document looks like.
Content from Mathematics
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do I add mathematical expressions to a LaTeX document?
Objectives
- Create Inline and Display Math Mode expressions in LaTeX
Math Mode
Typesetting mathematical expressions in LaTeX is one of its greatest strengths. We can mark up mathematical content in a logical way in what is known as math mode.
There are two kinds of math mode in LaTeX:
- Inline math mode: for typesetting math within a line of text
- Display math mode: for typesetting math on its own line
Inline Math Mode
Inline math mode is marked using a pair of dollar sign symbols
($ ... $
). It is also possible to use the notation
\(...\)
to mark inline math mode. Simple expressions are
entered without any special markup, and you’ll see that the math is
spaced out nicely and has letters in italic.
LATEX
\section{Mathematics}
There are two kinds of math mode in LaTeX: inline and display. Inline math mode is marked with
a pair of dollar signs, whereas display math mode is marked with a pair of square brackets.
\subsection{Inline Math Mode}
The Pythagorean theorem is $a^2 + b^2 = c^2$.
There are a lot of symbols and specialist math mode commands available in LaTeX:
- Superscripts:
x^2
- Subscripts:
x_1
- Greek letters:
\alpha
,\beta
,\gamma
, etc. - Operators:
\times
,\div
,\sin
,\log
, etc. - Fractions:
\frac{numerator}{denominator}
- Roots:
\sqrt{expression}
- Sums and integrals:
\sum
,\int
,\oint
, etc. - Brackets:
()
,[]
,{}
,\langle
,\rangle
, etc.
Display Math Mode
Display math mode uses the exact same commands as inline math mode,
but it is centered by default and is intended for larger equations that
are “part of a paragraph”. It is also started and ended with a pair of
square brackets (\[ ... \]
).
Callout
Remember that [
and ]
are special
characters in LaTeX, which is why we have to “escape” it with a
backslash(\
) here.
LATEX
\subsection{Display Math Mode}
The Fourier Transform is defined as:
\[
\hat{f}(\xi) = \int_{-\infty}^\infty f(x) e^{-2\pi i \xi x} \, dx
\]
Where:
\begin{itemize}
\item \( f(x) \) is the function we are transforming,
\item \( \hat{f}(\xi) \) is the Fourier Transform of \( f(x) \),
\item \( \xi \) is the frequency variable,
\item \( i \) is the imaginary unit.
\end{itemize}
Math Mode in LaTeX is not just for LaTeX users! It is also used other tools like Jupyter Notebooks, R Markdown and many markdown processors. There are even extensions for Google Docs and Microsoft Word that allow you to use LaTeX math mode.
Math in Enviroments
We can include math in an environment called equation
to
number the equations:
LATEX
\subsection{Math in Environments}
The quadratic formula is:
\begin{equation}
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
\label{eq:quadratic}
\end{equation}
This will allow us to refer to the equation later in the document with \cmd{ref} like this:
Refer to Equation \ref{eq:quadratic}.
We can now refer to this equation using the \ref
command, just like we did in the previous section:
The amsmath
Package
Mathematical notation is very rich, and the tools in the LaTeX kernel
are sometimes not enough to cover everything. The amsmath
package extends the capabilities of LaTeX for more complex mathematical
typesetting. Let’s try it out:
Add the following to your document:
(In the preamble)
(In the body)
LATEX
\subsection{The `amsmath` Package}
Solve the following recurrence for $ n,k\geq 0 $:
\[
Q_{n,0} = 1 \quad Q_{0,k} = [k=0];
\]
\[
Q_{n,k} = Q_{n-1,k}+Q_{n-1,k-1}+\binom{n}{k}, \quad\text{for $n$, $k>0$.}
\]
That look ok, but we really want the equations to be aligned
vertically, not centered on the page. We can use the align
environment from the amsmath
package to do this:
LATEX
\subsection{The `amsmath` Package}
Solve the following recurrence for $ n,k\geq 0 $:
\begin{align*}
Q_{n,0} &= 1 \quad Q_{0,k} = [k=0]; \\
Q_{n,k} &= Q_{n-1,k}+Q_{n-1,k-1}+\binom{n}{k}, \quad\text{for $n$, $k>0$.}
\end{align*}
The align*
environment makes the equations line up on
the amperstand (&
)
There’s far too many options to cover here, but the
amsmath
User Guide contains many more examples.
Challenges
Challenge 1: Can you do it?
See if you can write the following mathematical expression in LaTeX:
- Special Relativity: t’ = t / sqrt(1 - v^2 / c^2)
Challenge 3: The amsmath
package
and referencing equations
Add the following equation to your document: E = mc^2. For this, use
the amsmath
package and a numbered align
environment. Label the equation using \label
. Then, use the
\ref
command to refer to the equation in the text. You may
find the following LaTeX template helpful:
LATEX
\documentclass{article}
\usepackage{amsmath} % For better equation formatting
\begin{document}
\section{Referencing Equations}
We can include a numbered equation as follows:
\begin{equation}
E = mc^2
\label{eq:energy}
\end{equation}
Now, we refer to the equation in the text. The famous equation is \ref{eq:energy}.
\end{document}
Key Points
- Inline math mode is marked with
$ ... $
or\(...\)
- Display math mode is marked with
\[ ... \]
After this episode, here is what our LaTeX document looks like.
Content from Fonts and Spacing
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How can we set paragraph spacing in LaTeX?
- How can we customize text formatting in LaTeX?
- How can we align text in LaTeX?
Objectives
- Add custom spacing between paragraphs in LaTeX.
- Create a title page with custom text formatting.
Paragraph Spacing
A common style in LaTeX is to have no indents for paragraphs, but to
incorporate a blank line between them. We can achieve this using the
parskip
package.
We’re going to use another package here just to show off some
commands without having to write a lot of text: the lipsum
package. This package provides the \lipsum
command, which
generates “Lorem Ipsum” text.
Callout
Lorem Ipsum is a common piece of placeholder text used in publishing and graphic design. It is often used to demonstrate the visual form of a document without relying on meaningful content.
The text itself comes from the first-century BC work De finibus bonorum et malorum by Marcus Tullius Cicero.
In our document, we can now use a blank line to separate paragraphs:
LATEX
\section{Fonts and Spacing}
% Generate some "Lorem Ipsum" text
% The parameters mean "include paragraphs 1 thru 2" from the "Lorem Ipsum" text
\lipsum[1-2]
Compile the document and take a look at our section. You should see that our first paragraph has no indent, and there is no blank line between it and the following paragraph. The second paragraph does have an indent. This is the default behavior in LaTeX.
Now let’s add our package:
Keep an eye on the preview pane as you compile the document. You should see that the first paragraph now has a blank line between it and the second paragraph, and there is no indent on the first line of the second paragraph.
Forcing a New Line
Most of the time, you should not force a new line in your document;
you almost certainly want to use a new paragraph or parskip
instead. However, there are a few places where you might want
to force a new line:
- At the end of table rows
- Inside a
center
environment - In poetry (the
verse
environment)
To force a new line, we can use the \\
command.
Adding Explicit Space
We can insert a thin space (about half the normal thickness) use the
\,
command.
Callout
In math mode, there are also other commands:
-
\.
for a “dot” space -
\:
for a “colon” space -
\;
for a “thick” space -
\!
for a “negative” space -
\,
for a “thin” space
Very rarely, for example when creating a title page, you might want
to add explicit horizontal or vertical space. We can do this using the
\hspace
and \vspace
commands:
We can also use the \vfill
command to fill the remaining
space on a page. This is useful for centering content vertically on a
page.
Explicit Text Formatting
We’ve touched on this in previous episodes, but we can also use the following commands to format text explicitly:
-
\textbf{}
for bold text -
\textit{}
for italic text -
\textrm{}
for roman text -
\textsf{}
for sans serif text -
\texttt{}
for typewriter text -
\textsc{}
for small caps text
We can set the font size in the same way. All sizes are relative to the base font size:
-
\huge
for huge text -
\large
for large text -
\normalsize
for normal text -
\small
for small text -
\footnotesize
for footnote text
Text Alignment
We can align text using the following commands:
-
\centering
to center text -
\raggedright
to left-align text -
\raggedleft
to right-align text
Creating a Title Page
Using all of this, let’s create a simple title page for our document.
We’ll put this just after the \begin{document}
command, and
enclose everything in a titlepage
environment:
LATEX
\begin{titlepage}
\centering
\huge
\textbf{My Example Document}
\vspace{1cm}
\normalsize
\textit{An example of a LaTeX document}
\vfill
January 1, 2000
\end{titlepage}
Callout
The titlepage
environment is a special environment that
LaTeX uses to create a title page. It sets some simple formating rules,
like removing multiple columns and resetting the page number. It also
prevents styling rules we add like centering
from affecting
the rest of the document.
Inline instructor notes can help inform instructors of timing challenges associated with the lessons. They appear in the “Instructor View”
Challenges
Challenge 1: Create a Title Page with Custom Formatting
Using the content covered, create a title page with custom formatting. Your title page should have:
- A centered title “My Custom LaTeX Title Page” in large, bold text.
- A centered subtitle “A Sample Document with Custom Formatting” in italic text, smaller than the title.
- The date centered at the bottom of the page.
You can use the commands \vspace
and \vfill
to make fill blank space between the items and may find the following
LaTeX template helpful:
LATEX
\documentclass{article}
\begin{document}
\begin{titlepage}
\centering
\huge
\textbf{My Custom LaTeX Title Page}
\vspace{1cm} % Space between title and subtitle
\normalsize
\textit{A Sample Document with Custom Formatting}
\vfill % Fill remaining space
\large
January 1, 2025
\end{titlepage}
\end{document}
Challenge 2: Adjust Paragraph Spacing in Your Document
Create a LaTeX document with the following:
- Use the
parskip
package to adjust the paragraph spacing. - Generate some text using the
lipsum
package. - Ensure that paragraphs are separated by a blank line (without indentation).
Key Points
- Use the
parskip
package to add space between paragraphs - Force a new line with
\\
- Add explicit space with
\hspace
and\vspace
- Format text explicitly with
\textbf
,\textit
, etc. - Align text with
\centering
,\raggedright
, and\raggedleft
Content from Citations and References
Last updated on 2025-06-24 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do I add bibliographic references to my document?
- How do I format my references in LaTeX?
- How do I cite references in my document?
Objectives
- Learn how to use a reference database to manage references in LaTeX documents.
- Explore different ways of citing references in our document.
Citations and References
For bibliographic citations, while you can include references sources
directly in our document, usually you will get that information from one
or more external files. Such a file is a database of references,
containing the information in a processing-friendly format (which is
called BibTeX
). Using one or more reference databases lets
you re-use information and avoid manual formatting.
Reference Databases (BiBTeX)
Reference databases are normally referred to as BiBTeX
files, and have the extension .bib
. They contain one or
more entries, one for each reference, and within each are a series of
fields.
Create a new file in your project called
sample-references.bib
and add the following content:
BIBTEX
@article{Thomas2008,
author = {Thomas, Christine M.},
title = {The Fascinating World of Penguins},
journal = {Penguin Chronicles},
year = {2008},
pages = {7009-7024},
}
@book{Graham1995,
author = {Richard L. Graham and Lisa A. Harris},
title = {The Humble Paperclip: Master of the Modern Office},
publisher = {Scranton Press},
year = {1995},
}
This is an example of a BiBTeX file that contains a reference for an
article and another for a book. Each entry type starts with a the
@
symbol, followed by the type of the referencing item
(e.g. article
) and all information appears within a pair of
curly braces {}
.
The various fields are given in key-value format. Exactly which fields you need to give depends on the type of entry.
Callout
You might notice that in the author
field, each entry is
separated by the word and
. This is essential: the format of
the output needs to know which author is which.
You might also notice that in the article title, some entries are in an extra set of braces. This is to prevent any case-changing that might be applied to the title.
The BibTeX Format
Editing BiBTeX files by hand can be difficult and tedious. A number of tools exist to help you manage your reference files. You can find a list of sugggested tools in the references section.
We’re going to cover two different ways to include references in our
document: using the natbib
package and using the
biblatex
package. For the purposes of this workshop, we’ll
use biblatex
, but feel free to explore natbib
on your own - an identical example is provided in the
natbib
tab below.
Callout
There are many different bibliography styles available, and you can find a list of them at CTAN. Check if one of those bibligraphy and citation styles meets your requirements. If you want to finetune an existing one we suggest to take a look at biblatex-ext.
Inline instructor notes can help inform instructors of timing challenges associated with the lessons. They appear in the “Instructor View”
Challenges
Challenge 1: Try out the other example?
Go back up to the natbib
tab and try out the example
there. What differences do you notice?
The natbib
package is a bit more manual than
biblatex
. You have to specify the bibliography style and
the bibliography file separately, and the citation commands are a bit
more manual. This isn’t necessarily a bad thing, as it gives you more
control over the output. There’s no wrong answer, just personal
preference.
Challenge 2: Add another reference, then delete it.
Try adding the following reference to your
sample-references.bib
file:
BIBTEX
@book{Huff1954,
author = {Huff, Darrell},
title = {How to Lie with Statistics},
publisher = {W. W. Norton \& Company},
year = {1954},
}
Then, add a citation to this reference in your document. Try a couple different styles of citation commands. Then, once you have it working, delete the reference and re-compile your document. What happens?
You might expect removing the reference to either error or remove the citation from the text, but it doesn’t - instead we get a placeholder in the text and a warning in the log. A missing reference is not so critical an error that we can’t render the document, but we should probably fix it.
Challenge 3: What’s wrong with this?
We have the following reference in our document:
BIBTEX
@misc{mikolov2013,
title={Efficient Estimation of Word Representations in Vector Space},
author={Tomas Mikolov and Kai Chen and Greg Corrado and Jeffrey Dean},
year={2013},
eprint={1301.3781},
archivePrefix={arXiv},
primaryClass={cs.CL},
url={https://arxiv.org/abs/1301.3781},
}
We are using biblatex to manage our references, and we identify this reference in the text like this:
When we compile our document, we see the following error:
OUTPUT
The Word2Vec algorithm (mikolov) is a popular method for generating word embeddings.
What’s wrong with this reference? How can we fix it?
We are referencing the key mikolov
in our document, but
the key in our BiBTeX file is mikolov2013
. We need to
update our citation command to \autocite{mikolov2013}
. Note
that LaTeX still compiles the document, but it gives us a warning that
the reference is missing and uses the key as a placeholder. You might
use this to temporarily mark a reference that you haven’t added yet,
just be sure to clear all of your warnings before finializing your
document.
Key Points
- References are stored in a reference database, seperate from the LaTeX document.
- BiBTeX files are used to store references in a processing-friendly
format and have the extension
.bib
. - There are multiple libraries available to manage references in LaTeX
documents, including
natbib
andbiblatex
. - We can use the
\cite
command or one of its variants to cite references in our document.
Content from Structuring Sources
Last updated on 2025-05-06 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How can we make it easier to manage large LaTeX projects?
- How can we reuse parts of our LaTeX document in other documents?
- How can we structure our LaTeX project?
Objectives
- Learn how to use commands to include other files in your LaTeX document
- Restructure a LaTeX project to use multiple files
Project Structure
So far, we’ve been putting all of our LaTeX code into a single document. This is fine for small projects, but even with what we have here so far, you might have started to feel like things are getting a little unwieldy and hard to manage.
One of the great things we can do with LaTeX is break our document up into smaller “sources”, which allows us to work on each part of the document separately. You can imagine this might be helpful when working on a large document with multiple chapters, where each chapter is a separate file. You might also find this useful when you intend to reuse parts of your document in other documents, like title pages, tables of contents, or lists of figures.
This also helps with collaboration, as multiple people can work on different parts of the document at the same time without having to worry about conflicts.
Commands
There are two important commands to know when working with multiple sources:
\input{filename}
\include{filename}
The \input{filename}
command will include the contents
of the file filename.tex
at the point where the command is
called as though it was typed directly into the main document. This can
be useful for things that are not, for example, separate chapters, but
rather things like a title page, a table of contents, or a list of
figures.
The \include{filename}
command will do the same thing,
but it will also start a new page before including the file. This is
useful for including separate chapters or sections of your document.
When you use \include{filename}
you can also use
\includeonly{filename1,filename2}
in your preamble. This
will then only insert the file mentioned but respect all other files
regarding e.g. pagenumber, references etc.
Input Example
Let’s try out using the \input{filename}
command. We’ll
create a new file called input_example.tex
in our project
directory with the following contents:
LATEX
\cmd{Input} is useful for including things as if they were typed directly into the main document.
Things like commands don't have to be defined in the included file, as long as they are defined in
the main document.
Then, in our main.tex
document, let’s add the following
section:
When we compile our document, we should see the contents of
input_example.tex
included in our main document.
Include Example
Let’s try out using the \include{filename}
command.
We’ll create a new file called include_example.tex
in our
project directory with the following contents:
LATEX
\cmd{Include} is useful for including things as if they were typed directly into the main document,
but it will also start a new page before including the file.
Then, in our main.tex
document, let’s add the following
section:
When we compile our document, we should see the contents of
include_example.tex
, however this time the content will
have included a new page before the content.
Callout
Another important thing to note about the
\include{filename}
command is that it cannot contain
another \include{}
command - this will result in an
error.
You can, however, use \input{}
inside an
\include{}
command or an \input{}
command
inside another \input{}
command.
Updating Our Project
Now that we’ve seen how to use the \input{filename}
and
\include{filename}
commands, let’s refactor our project to
use them. We’ll take each section and put it in it’s own file, then
include the files in our main.tex
document. This will main
our main document easier to read and manage, while separating out the
content into more manageable pieces.
Let’s also organize our files a little bit. Instead of putting everything in the “root” directory of this project, we’ll create a folder called “content” and put our section files in there.
Separating Our Sections
Let’s make files in our “content” directory for each of our sections:
content/sections.tex
content/lists.tex
content/graphics.tex
content/tables.tex
content/cross-references.tex
content/mathematics.tex
content/fonts-and-spacing.tex
content/reference-databases.tex
We’ll move the content from each section into the corresponding file.
content/lists.tex
LATEX
\section{Lists}
There are two types of lists: ordered and unordered.
\subsection{Ordered}
Ordered lists do not have numbers associated with each item.
\begin{enumerate}
\item Item 1
\item Item 2
\item Item 3
\end{enumerate}
\subsection{Unordered}
Unordered lists are just a series of items preceded by a marker.
\begin{itemize}
\item Item 1
\item Item 2
\item Item 3
\end{itemize}
\end{document}
content/graphics.tex
LATEX
\section{Graphics}
We can include \kw{images} in our document using the \cmd{graphicx} package, which lets us use the
\cmd{includegraphics} command.
\includegraphics{figures/example-image.png}
\subsection{Small Image}
We can pass parameters to the \cmd{includegraphics} command to adjust the appearance of the image.
\includegraphics[height=2cm]{figures/example-image.png}
Other possible options include:
\begin{itemize}
\item width: the width of the image
\item scale: the scaling factor of the image
\item angle: the angle of rotation of the image
\item clip: whether to clip the image to its bounding box
\item trim: trim the image by a specified amount
\item draft: display a box instead of the image
\end{itemize}
\subsection{Centered Image}
By placing the \cmd{includegraphics} command inside a center environment, we can center the
image on the page.
\begin{center}
\includegraphics[height=2cm]{figures/example-image.png}
\end{center}
\subsection{Floating Image}
\kw{Floating images} can move around the page as text is added or removed. We can use the
\cmd{figure}environment to create a floating image.
\begin{figure}[ht]
\centering
\includegraphics[height=2cm]{figures/example-image.png}
\end{figure}
Control the position of a floating image by passing paratmeters to the \cmd{figure} environment:
\begin{itemize}
\item h: Place the float "here" (where it appears in the code)
\item t: Place the float at the "top" of the page
\item b: Place the float at the "bottom" of the page
\item p: Place the float on a "page" by itself
\end{itemize}
\subsection{Caption}
We can add a \kw{caption} to our floating image by using the \cmd{caption} command inside of the
\cmd{figure} environment.
\begin{figure}[h]
\centering
\includegraphics[height=2cm]{figures/example-image.png}
\caption{This is a caption for our image.}
\end{figure}
content/tables.tex
LATEX
\section{Tables}
\kw{Tables} are defined using the \cmd{tabular} environment.
\input{tables/basic-table}
\subsection{Tables with Horizontal Lines}
We can use the \cmd{\textbackslash toprule}, \cmd{\textbackslash midrule}, and
\cmd{\textbackslash bottomrule} commands from the \cmd{booktabs} package to create horizontal
lines in our table.
\input{tables/table-with-horizontal-lines}
\subsection{Partial Horizontal Lines}
The \cmd{\textbackslash cmidrule} command can be used to create partial horizontal lines in a
table. The command accepts the arguments {number-number}, where the first number is the column to
start the line and last number is the column to end the line.
\input{tables/table-with-partial-horizontal-lines}
\subsection{Merging Cells}
Merge cells horizontally using the \cmd{\textbackslash multicolumn} command. This command takes
three arguments:
\begin{itemize}
\item The number of cells which should be merged
\item The alignment of the merged cell (l, c, or r)
\item The contents of the merged cell
\end{itemize}
\input{tables/table-with-merged-cells}
content/cross-references.tex
LATEX
\section{Cross References}
\label{sec:cross-references}
\subsection{Material for the Introduction}
In this section, we introduce two new concepts:
\begin{tabular}{cp{9cm}}
Command & Description \\
\toprule
\kw{label} & Marks a spot in the document \\
\kw{ref} & Refers to a marked spot in the document \\
\bottomrule
\label{tab:cross-reference-commands}
\end{tabular}
We can \kw{refer} to the section with the \cmd{ref} command, like this: \ref{sec:cross-references}.
We can likewise refer to the table like this: \ref{tab:cross-reference-commands}.
content/mathematics.tex
LATEX
\section{Mathematics}
There are two kinds of math mode in LaTeX: inline and display. Inline math mode is marked with
a pair of dollar signs, whereas display math mode is marked with a pair of square brackets.
\subsection{Inline Math Mode}
The Pythagorean theorem is $a^2 + b^2 = c^2$.
\subsection{Display Math Mode}
The Fourier Transform is defined as:
\[
\hat{f}(\xi) = \int_{-\infty}^\infty f(x) e^{-2\pi i \xi x} \, dx
\]
Where:
\begin{itemize}
\item \( f(x) \) is the function we are transforming,
\item \( \hat{f}(\xi) \) is the Fourier Transform of \( f(x) \),
\item \( \xi \) is the frequency variable,
\item \( i \) is the imaginary unit.
\end{itemize}
\subsection{Math in Environments}
The quadratic formula is:
\begin{equation}
x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}
\label{eq:quadratic}
\end{equation}
This will allow us to refer to the equation later in the document with \cmd{ref} like this:
Refer to Equation \ref{eq:quadratic}.
\subsection{The `amsmath` Package}
Solve the following recurrence for $ n,k\geq 0 $:
\[
Q_{n,0} = 1 \quad Q_{0,k} = [k=0];
\]
\[
Q_{n,k} = Q_{n-1,k}+Q_{n-1,k-1}+\binom{n}{k}, \quad\text{for $n$, $k>0$.}
\]
content/reference-databases.tex
LATEX
\section{Reference Databases}
One of the best features of LaTeX when writing academic documents is the ability to easily and
confidently \kw{cite references}.
We can cite the article by Thomas (e.g. with `\textbackslash autocite\{Thomas2008\}`) and it will show up in the references.
You should see that the citation appears in the text (`(Thomas et al. 2008)`), and the reference
now appears at the end of the document. \cmd{\textbackslash autocite} is a command that automatically chooses the
citation style for you.
Some additional commands that are available in `biblatex`:
\begin{itemize}
\item `\textbackslash cite\{key\}` or `\textbackslash cite\{key1, key2\}`: Cite the reference with the given key
\item `\textbackslash cites\{key1\}\{key2\}\{key-n\}`: Cite multiple references.
\item `\textbackslash usepackage\{\}\textbackslash parentcite\{key\}`: Cite the parent reference of the given key.
\item `\textbackslash autocite\{key\}`: Automatically choose the citation style.
\item `\textbackslash smartcite\{key\}`: Automatically choose the citation style, but with more control.
\item `\textbackslash footcite\{key\}`: Cite the reference in a footnote.
\end{itemize}
A plain citation looks like this \cite{Graham1995}, while multiple citations look like this
\cites{Graham1995}[see][p. 42]{Thomas2008}. We already used autocite, but we can also use the
similar smartcite \smartcite{Graham1995}. The benefit with smartcite is that you
can setup that e.g. all references should go into a footnote. You can continue
using smartcite when you are *in* a footnote and it will then detect that there
is no need for creating another footnote but behaving like autocite.
Then, in our main.tex
document, we’ll include each of
these files using the \input{filename}
:
LATEX
\include{content/sections}
\include{content/lists}
\include{content/graphics}
\include{content/tables}
\include{content/cross-references}
\include{content/mathematics}
\include{content/fonts-and-spacing}
\include{content/reference-databases}
Callout
Note that the \include{filename}
command does not
require the .tex
extension. LaTeX will assume that the file
is a .tex
file if no extension is provided.
This is also true for someof the other commands we’ve seen, such as
\includegraphics{}
. It is personal preference whether you
include the extension or not.
When we compile our document, we should see the same content as before, but now we can make changes in our content files, and the changes will be reflected in our main document.
Other Files
While we’re at it, let’s also create files for our packages, commands, and title page. We’ll also put these into their own directory called “preamble”:
preamble/packages.tex
preamble/custom-commands.tex
preamble/titlepage.tex
Our New main.tex
Our main.tex
document should now look like this:
LATEX
% This command tells LaTeX what kind of document we are creating (article).
\documentclass{article}
\input{preamble/packages}
\input{preamble/custom-commands}
\addbibresource{sample-references.bib}
% Everything before the \begin{document} command is called the preamble.
\begin{document} % The document body starts here
\include{content/titlepage}
Hello World!
This is my first \kw{LaTeX} document.
\include{content/sections}
\include{content/lists}
\include{content/graphics}
\include{content/tables}
\include{content/cross-references}
\include{content/mathematics}
\include{content/fonts-and-spacing}
\include{content/reference-databases}
\printbibliography
\end{document}
Callout
Note that we still need to put the content in the appropriate order.
For example, you can’t add \input{includes/packages}
at the
end of the document, as it needs to be included before the document
starts.
Challenges
Challenge 1: Refactor Your Document with Multiple Files
Refactor the following LaTeX document to use multiple files.
LATEX
% This is the main document: main.tex
\documentclass{article}
\begin{document}
\begin{titlepage}
\centering
\huge
\textbf{My Custom LaTeX Title Page}
\vspace{1cm} % Space between title and subtitle
\normalsize
\textit{A Sample Document with Custom Formatting}
\vfill % Fill remaining space
\large
January 1, 2025
\end{titlepage}
\section{Tables}
\begin{tabular}{lll}
Fruit & Quantity & Price \\
Apple & 5 & 1.50 \\
Banana & 6 & 2.00 \\
Orange & 4 & 1.20 \\
\end{tabular}
\section{Graphics}
\begin{figure}[ht]
\centering
\includegraphics[height=2cm]{example-image.PNG}
\caption{This is a caption for our image.}
\end{figure}
\end{document}
- Separate the content into different files for the sections by
tables.tex
andgraphics.tex
. - Organize the file for the titlepage in a folder named “includes” and
name the file
titlepage.tex
. - Organize the files for tables and graphics in a folder named “content”.
- Use the
\input
command to include the titlepage and the content in yourmain.tex
document.
LATEX
% This is the main document: main.tex
\documentclass{article}
\begin{document}
% Include title page
\input{includes/titlepage}
% Include content from different files in the "content" folder
\input{content/sections}
\input{content/lists}
\input{content/graphics}
\input{content/tables}
\input{content/cross-references}
\input{content/math}
\input{content/text-and-spacing}
\end{document}
Challenge 2: Why did we do this?
In our content/tables.tex
file, we have a bunch of
\input{}
commands for the tables instead of writing the
tables directly in the file. Why did we do this? What is the benefit of
doing this?
Using an \input
command inserts the table contents
directly into the document as though it was typed, which means that we
can reuse the same table in multiple documents without having to copy
paste it. For example, if we were making a presentation in LaTeX, we
could use the same table in our presentation. This means that if we make
a change to the table, it will be reflected in all of the documents in
which we use it.
(This reflects the programming principle of “Don’t Repeat Yourself” (DRY)!)
Challenge 3: Restructuring a larger document?
There isn’t a specific correct answer for this challenge, but one idea might be something that looks like this:
├── main.tex
├── preamble.tex
├── refereces.bib
├── content/
│ ├── introduction.tex
│ ├── model_architecture.tex
│ ├── model_results.tex
│ └── conclusion.tex
├── tables/
└── model_results.tex
Key Points
- LaTeX projects can contain many files that reference each other
- The
\input{filename}
and\include{filename}
commands allow you to include the contents of other files in your document - The
\frontmatter
,\mainmatter
,\backmatter
, and\appendix
commands help structure your document
Content from Fonts and Encodings
Last updated on 2025-05-06 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do you write a lesson using R Markdown and sandpaper?
Objectives
- Explain how to use markdown with the new lesson template
- Demonstrate how to include pieces of code, figures, and nested challenge blocks
documentclass Parameters
In an earlier episode we learned that we can change the font size of
the entire document by changing the \documentclass
command.
For example, we can change the font size to 12pt by using:
But we can add other parameters to this command to change the overall layout of the document. For example, we can set the size of the document to A4 paper by using:
We can also change the entire document to a two-column layout by using:
And we can of course combine these options:
Fonts
We saw earlier that we can create commands of our own in LaTeX, but
there is also a renewcommand
command that let’s us change
the definition of an existing command. This might be useful if you want
the definition of a command to change throughout the document, however
there are also some commands that are pre-defined that we can modify
with this command.
For Example, we can change the font of the entire document by adding
the following line to the preamble/custom-commands.tex
file:
LATEX
% Change the font of the entire document to a monospace font
\renewcommand{\familydefault}{\ttdefault}
When you compile the document you should see something like this:
IMAGE GOES HERE
More Fonts
Unfortunately, the default LaTeX installation does not come with many
fonts. However, there are additional packages that you can include if
you are looking for a specific font. Let’s try making our document look
like it’s using the Times New Roman
font. To do this, all
we need to do is add the following import to the
preamble/packages.tex
file:
Callout
You can find a large selection of fonts at The LaTeX Font Catalogue, complete with examples of how to use them in your document.
Challenges
Challenge 1:
We saw how to change the font of the entire document using the
\renewcommand
command. But what if only want a specific
section of the document to be in a different font? What would we have to
modify in the following code to make the text in the first
\section{}
command use a different font?
Challenge 2:
Key Points
- Use
.md
files for episodes when you want static content - Use
.Rmd
files for episodes when you need to generate output - Run
sandpaper::check_lesson()
to identify any issues with your lesson - Run
sandpaper::build_lesson()
to preview your lesson locally
Content from Error Handling
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- What do I do when I get an error message?
Objectives
- Understand how to interpret error messages in LaTeX
- Learn how to fix common errors in LaTeX documents
Error Handling
Error messages in LaTeX can often be difficult to understand, especially if you’re new to the language. However there are a few common errors that we can learn to recognize and fix, and a few techniques we can use to debug our documents based on the error messages we receive.
Anatomy of an Error Message
Way back in Episode 2 - Document Structure, we saw some error messages - let’s take a closer look at one of them and see what it tells us.
Let’s re-introduce the issue: we’ll change the
\documentclass
command in main.tex
to
\documnetclass
…
Ok, that’s a lot of errors! Let’s look at the very first one in the list:
In the red bar at the top, we have both the name of the error message
(“Unidentified control sequence”) and the file and line number where the
error occurred (main.tex, 2
). This gives us a great
starting point to identify the issue. Now let’s look at the contents of
the message:
The compiler is having trouble understanding a command you have used. Check that the command is
spelled correctly. If the command is part of a package, make sure you have included the package in
your preamble using \usepackage{...}.
This is Overleaf’s way of trying to make a more helpful version of the error message than LaTeX itself. We can see the actual error message from LaTeX just below:
l.2 \documnetclass
{article}
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.
Of course, we know what the error was, so we can just fix it by
changing \documnetclass
back to
\documentclass
.
Callout
In general, the first error message in the list is the most useful one to look at. The other error messages are often just a result of the first error cascading down the document, so fixing the first one will often fix the rest of them too.
Errors vs Warnings vs Information
Not all messages are equal! LaTeX has three different types of messages:
-
Error
: This is a serious issue that will prevent your document from compiling. You need to fix this before you can continue. -
Warning
: This is a less serious issue that may not prevent your document from compiling, but it may cause issues with the output. You should still try to fix this, but it may not be critical. -
Information
: This is just a message that provides additional information about the document. You can usually ignore this.
In Overleaf, error messages are shown in red, warnings are shown in yellow, and information messages in blue.
Fixing a Common Error
This time, instead of introducing an error into our document, let’s
create a new file called my-error-example.tex
and add the
following code:
LATEX
\documentclass{article}
\begin{document}
\section{Introduction}
\label{sec:intro}
Hello there!
This document intentionally contains a very common latex error in the following section. Use the
error message to try to identify and fix the error.
\section{A section with an error}
\label{sec:error}
As mentioned in section \ref{sec:intro}, this document contains an error.
We have a list of items in our store:
\begin{itemize}
\item Camera
\item Printer (out of stock)
\item Cellphone
\end
Our Current Inventory:
\begin{tabular}{|l|l|}
\hline
Item & Quantity \\
\hline
Camera & 5 \\
Printer & 0 \\
Cellphone & 10 \\
\hline
\end{tabular}
\end{document}
Challenges
Challenge 1: Identify the error
Take a look at the following LaTeX excerpt:
LATEX
\documentclass{article}
\begin{document}
My Amazing Content: $\alpha = \fraction{1}{(1 - \beta)^2}$
\end{document}
Attempting to compile this document results in the following error message:
! Undefined control sequence.
l.4 $\alpha = \fraction
{1}{(1 - \beta)^2}$
The control sequence at the end of the top line
of your error message was never \def'ed. If you have
misspelled it (e.g., `\hobx'), type `I' and the correct
spelling (e.g., `I\hbox'). Otherwise just continue,
and I'll forget about whatever was undefined.
Without running the code, can you identify the issue?
The error message indicates that the command \fraction
is not defined. The correct command should be \frac
.
Challenge 2: Identify the error
Here’s another LaTeX excerpt:
LATEX
\documentclass{article}
\usepackage{booktab}
\begin{document}
More Amazing Content!
\end{document}
The following error message appears when you try to compile this document:
! LaTeX Error: File `booktab.sty' not found.
Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)
Why is this error occurring? What is the solution?
The error message indicates that the package booktab
is
not found. The correct package name should be booktabs
Challenge 3: Why do I get this warning?
The following code generates a warning message:
LATEX
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\section{Adding a rotated image}
We can rotate an image by setting the "angle" parameter:
\includegraphics[scale=2, angle=45]{figures/example-image.png}
\end{document}
The text of the warning message is:
Overfull \hbox (390.7431pt too wide) in paragraph at lines 10--11
[][]
[]
[1
{/usr/local/texlive/2024/texmf-var/fonts/map/pdftex/updmap/pdftex.map}]
Overfull \vbox (170.7431pt too high) has occurred while \output is active []
[2 <./figures/example-image.png>] (./output.aux)
The document compiles successfully, but the warning message won’t go away. Why is this happening? How can you fix it?
The message is indicating that the image is too wide for the page, which is causing an “overfull hbox” (overfull horizontal box) error. This is a common issue when including images in LaTeX. The warning will not prevent the document from compiling, but it may point to something we should take a look at, in this case, an image that flows off the page.
Key Points
- Use
.md
files for episodes when you want static content - Use
.Rmd
files for episodes when you need to generate output - Run
sandpaper::check_lesson()
to identify any issues with your lesson - Run
sandpaper::build_lesson()
to preview your lesson locally
Content from Documentation and Finding Help
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- Where can I find help for writing LaTeX documents?
- How do I find out what commands a package provides?
Objectives
- Learn how to find help for LaTeX documents
CTAN (The Comprehensive TeX Archive Network)
A large number of LaTeX packages are available on CTAN. CTAN contains packages and related documentation for many widely used LaTeX packages. You can search the archive for specific strings, or browse by category.
Project pages
Individual package pages often contain links to detailed documentation, including PDF manuals and example files. Additional you can find links to the package’s source code, and information about the author(s) and ratings from other users.
Texdoc
Texdoc provides a modern interface for looking up package documentation. Much like CTAN, you can search for packages and view their documentation.
Callout
Texdoc is also available as a command line tool, which queries the same database of information, but allows you to search for packages and documentation from the command line.
Other Resources
As with any language there are many other resources that you can make use of. The Stack Exchange for LaTeX is a great place to ask questions and find answers to common problems.
Challenges
Challenge 1: Find it in the documentation!
We have the geometry package loaded in our document, and we know we want to use to to set the margins of the document, but we want to set them to 2cm on the left and right, and 4cm on the top and bottom. We also want to set the per size to A4. Can you find the documentation for the command and see how to do this?
Challenge 2: Find a specific package.
We have a very particular document we want to create - we are talking about specific positions on a chess board and we want to render these directly in the document. Can you find a package that will help us do this? Can you make a simple chess board using this package?
Searching either CTAN or Texdoc for “chess” will return a number of
packages. We’ll use the chessboard
package for our example.
To make a simple chess board, we can use the chessboard
command:
Key Points
- CTAN is a large archive of LaTeX packages and documentation
- Texdoc is a website & command line tool for searching LaTeX documentation
Content from Loading and Manipulating Data
Last updated on 2025-05-05 | Edit this page
Estimated time: 12 minutes
Overview
Questions
- How do you write a lesson using R Markdown and sandpaper?
Objectives
- Explain how to use markdown with the new lesson template
- Demonstrate how to include pieces of code, figures, and nested challenge blocks
Introduction
This is a lesson created via The Carpentries Workbench. It is written
in Pandoc-flavored Markdown
for static files (with extension .md
) and R Markdown for dynamic files
that can render code into output (with extension .Rmd
).
Please refer to the Introduction to The
Carpentries Workbench for full documentation.
What you need to know is that there are three sections required for a valid Carpentries lesson template:
-
questions
are displayed at the beginning of the episode to prime the learner for the content. -
objectives
are the learning objectives for an episode displayed with the questions. -
keypoints
are displayed at the end of the episode to reinforce the objectives.
Inline instructor notes can help inform instructors of timing challenges associated with the lessons. They appear in the “Instructor View”
Challenge 1: Can you do it?
What is the output of this command?
R
paste("This", "new", "lesson", "looks", "good")
OUTPUT
[1] "This new lesson looks good"
Challenge 2: how do you nest solutions within challenge blocks?
You can add a line with at least three colons and a
solution
tag.
Figures
You can use pandoc markdown for static figures with the following syntax:
{alt='alt text for accessibility purposes'}
Math
One of our episodes contains \(\LaTeX\) equations when describing how to create dynamic reports with {knitr}, so we now use mathjax to describe this:
$\alpha = \dfrac{1}{(1 - \beta)^2}$
becomes: \(\alpha = \dfrac{1}{(1 - \beta)^2}\)
Cool, right?
Key Points
- Use
.md
files for episodes when you want static content - Use
.Rmd
files for episodes when you need to generate output - Run
sandpaper::check_lesson()
to identify any issues with your lesson - Run
sandpaper::build_lesson()
to preview your lesson locally