An In-Depth Guide to Common Mistakes and Advanced Techniques
LaTeX is a powerful typesetting system that has become the standard for producing scientific and mathematical documents of high typographical quality. Its strengths lie in its ability to handle complex structures and its extensive customization capabilities. However, its complexity can also lead to common mistakes that can be challenging to troubleshoot, even for experienced users. To this end, I present this comprehensive guide to help you navigate these pitfalls. Each point is detailed with thorough explanations, examples, solutions, and alternative approaches, ensuring the information is invaluable for your LaTeX mastery.
LaTeX’s extensive capabilities allow for the creation of complex documents with precise control over formatting and structure. However, its steep learning curve can lead to common mistakes that hinder productivity and document quality. This guide aims to equip you with the knowledge to avoid these pitfalls, optimize your LaTeX workflow, and harness advanced techniques, which are valuable for researchers preparing scholarly papers.
{}
LaTeX uses braces {}
to group content and define the scope of commands. Missing or misplacing braces can lead to compilation errors or unintended formatting.
Runaway argument?
or Extra }, or forgotten \endgroup
.\textbf{This is bold text.
The \textbf{}
command applies bold formatting to the text within the braces. LaTeX cannot determine where the command ends without a closing brace, resulting in an error.
Ensure every opening brace {
has a corresponding closing brace }
.
\textbf{This is bold text.}
Consider using a linter or code analysis tool that checks for unbalanced braces and other syntax errors as you type. This proactive approach can prevent errors before they occur.
Using commands that LaTeX does not recognize, often due to typos or missing packages, leads to Undefined control sequence
errors.
Undefined control sequence
.\begin{document}
\includegraphics{image.png}
\end{document}
The \includegraphics{}
command is provided by the graphicx
package. Without including this package in the preamble, LaTeX does not recognize the command.
Include the necessary package in the preamble.
\documentclass{article}
\usepackage{graphicx}
\begin{document}
\includegraphics{image.png}
\end{document}
Use the \RequirePackage{}
directive in custom class or package files to ensure necessary packages are always loaded, especially when collaborating with others.
Certain characters have special meanings in LaTeX and cannot be used directly in text. These include #
, %
, $
, &
, _
, {
, }
, ^
, ~
, and \
.
Missing $ inserted
or Undefined control sequence
.The cost is $100 & tax included.
The &
character is used for alignment in tables and arrays. Using it outside of these environments without escaping causes an error.
Escape special characters by prefixing them with a backslash \
.
The cost is \$100 \& tax included.
Use the verbatim
Environment: For code snippets or text where special characters should be displayed as-is.
\begin{verbatim}
The cost is $100 & tax included.
\end{verbatim}
Use the \texttt{}
Command: For inline monospace text.
Use the command \texttt{git status} to check the repository status.
Use the listings
or minted
package to handle special characters automatically and provide syntax highlighting for code listings.
Overfull or underfull boxes occur when LaTeX cannot properly fit text within the specified margins, leading to too wide or too narrow lines.
Overfull \hbox
or Underfull \hbox
.This long line of text will likely cause an overfull hbox warning because it cannot be broken properly.
LaTeX tries to adjust the spacing to justify text, but it reports overfull or underfull boxes when it cannot. Long words or URLs without breakpoints exacerbate the issue.
\-
.Use the microtype
Package: Enhances justification and hyphenation.
\usepackage{microtype}
\usepackage{microtype}
This long line of text will likely cause an over\-full hbox warning because it cannot be broken properly.
\sloppy
or set \tolerance=1000
to allow more flexible spacing.url
or breakurl
package to manage line breaks in URLs.Set \emergencystretch=3em
to allow LaTeX to adjust spacing in emergency situations without affecting overall formatting.
Figures and tables (floats) only sometimes appear where you expect them due to LaTeX’s float placement algorithm and incorrect placement specifiers.
\begin{figure}
\includegraphics{image.png}
\caption{An example image}
\label{fig:example}
\end{figure}
No placement specifier is provided, so LaTeX defaults to [tbp]
.
LaTeX places floats according to allowed positions:
h
(here): Place the float where it appears in the source code.t
(top): At the top of a page.b
(bottom): At the bottom of a page.p
(page of floats): On a dedicated float page.LaTeX uses its algorithm without explicit instructions, which may not align with your expectations.
Specify float placement options to guide LaTeX.
\begin{figure}[htbp]
\centering
\includegraphics{image.png}
\caption{An example image}
\label{fig:example}
\end{figure}
[htbp]
vs. [htb]
[htbp]
: Allows placement here, at the top or bottom of a page, or on a separate float page (p
). Including p
gives LaTeX more flexibility when placing the float.[htb]
: Allows placement here, at the top or bottom of a page, but not on a separate float page. Omitting p
can cause floats to pile up if they do not fit the specified positions.!
Modifier: [!htbp]
tells LaTeX to ignore certain restrictions and try harder to place the float as specified.Force Exact Placement with the float
Package:
\usepackage{float}
\begin{figure}[H]
\centering
\includegraphics{image.png}
\caption{An example image}
\label{fig:example}
\end{figure}
[H]
specifier forces the float to appear precisely where it is in the code, which can disrupt the document’s flow.Use the placeins
package and the \FloatBarrier
command to prevent floats from moving past a certain point, such as the end of a section.
\usepackage{placeins}
...
\section{Results}
% Figures and tables
\FloatBarrier
Failing to correctly enter or exit math mode results in incorrect formatting and errors.
Missing $ inserted
.The solution to ax + b = 0 is x = -b/a.
Mathematical expressions need to be enclosed in $...$
or \[...\]
to be typeset correctly.
Ensure all mathematical content is within math mode delimiters.
The solution to $ax + b = 0$ is $x = -b/a$.
Use \( ... \)
and \[ ... \]
for inline and display math mode, respectively.
The solution to \( ax + b = 0 \) is \( x = -\frac{b}{a} \).
Use the amsmath
package for enhanced mathematical typesetting capabilities, providing environments like align
, gather
, and multline
.
\label
and \ref
CommandsIncorrectly placing \label
commands or not using \ref
and \pageref
properly leads to broken or incorrect cross-references.
\section{Introduction}
\label{sec:intro}
As discussed in Section \ref{sec:intro}, ...
If \label
is not immediately after the \section
command, it may not correctly capture the section number.
To correctly reference the number, the \label
command should come immediately after the counter-stepping command (like \section
, \caption
, etc.).
Place \label
immediately after the sectioning or captioning command.
\section{Introduction}\label{sec:intro}
As discussed in Section \ref{sec:intro}, ...
Use Meaningful Labels: To organize labels, use prefixes like sec:
, fig:
, and tab:
.
\section{Methodology}\label{sec:method}
See Figure~\ref{fig:example} for an illustration.
Consider using the cleveref
package to automate reference formatting and reduce errors for complex documents.
Neglecting to include packages that provide essential commands or functionalities results in errors or missing features.
Undefined control sequence
.Using \mathbb{R}
without including the amssymb
package.
Let $x \in \mathbb{R}$.
The \mathbb{}
command is provided by the amssymb
package.
Include the necessary package in the preamble.
\usepackage{amssymb}
Let $x \in \mathbb{R}$.
Create a personal package or class file that includes frequently used packages for consistency across documents.
Using characters that are not supported by the default font encoding leads to errors or missing characters.
Command \textquotedbl unavailable in encoding OT1
.Using accented characters without specifying the proper font encoding.
El Niño phenomenon affects climate patterns.
By default, LaTeX uses the OT1 font encoding, which does not support accented characters directly.
Include the fontenc
and inputenc
packages.
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
El Niño phenomenon affects climate patterns.
Set the document to use modern fonts and encoding from the start to avoid encoding issues.
Saving files in the wrong encoding causes LaTeX to misinterpret special characters.
Writing the document with UTF-8 characters but saving it in ANSI encoding.
LaTeX reads the file according to the specified encoding. Mismatches between file encoding and declared encoding lead to errors.
\usepackage[...]{inputenc}
with the file encoding.\usepackage[utf8]{inputenc}
Ensure all team members use the same encoding settings to prevent conflicts when collaborating.
\sin
, \log
, etc.)Not using the proper commands for mathematical operators leads to incorrect formatting, such as operators appearing italicized like variables.
Let $y = sin(x) + log(x)$.
In math mode, LaTeX treats letters as variables and italicizes them. Without proper commands, “sin” and “log” are interpreted as products of variables s
, i
, n
, etc.
Use LaTeX’s built-in commands for standard mathematical operators.
Let $y = \sin(x) + \log(x)$.
Use \operatorname{}
for Custom Operators:
Let $y = \operatorname{customFunc}(x)$.
Define New Operators with \DeclareMathOperator
:
\usepackage{amsmath}
\DeclareMathOperator{\sech}{sech}
Let $y = \sech(x)$.
If you need an operator with limits like \sum
or \lim
, use \DeclareMathOperator*
:
\DeclareMathOperator*{\Max}{Max}
Let $\Max_{x \in S} f(x)$.
This ensures proper formatting and placement of limits.
LaTeX may not automatically provide appropriate spacing in mathematical expressions, especially around certain symbols or complex equations.
If $x>y$, then $f(x)=g(y)$.
LaTeX does not always insert adequate spacing around relational operators (=
, <
, >
) and between function names and variables.
Use spacing commands in math mode to adjust space as needed.
If $x > y$, then $f(x) = g(y)$.
The default spacing is usually acceptable, but if more space is needed:
If $x \, > \, y$, then $f(x) \, = \, g(y)$.
\,
: Thin space\:
: Medium space\;
: Thick space\!
: Negative thin space\quad
: Space equal to the current font size\qquad
: Double \quad
Use \mathrel{}
for Relational Operators:
If $x \mathrel{>} y$, then $f(x) \mathrel{=} g(y)$.
Define custom commands for frequently used spaced expressions:
\newcommand{\sgeq}{\; \geq \;}
Use as:
If $x \sgeq y$, then...
This ensures consistent spacing throughout your document.
\mid
vs. |
in Math ModeUsing the vertical bar |
instead of \mid
in mathematical expressions can result in incorrect spacing, affecting the readability and meaning of expressions involving conditional probabilities or set notation.
P(A|B) = \frac{P(A \cap B)}{P(B)}
In math mode, |
is treated as a math operator with binary relation spacing, which may not be appropriate for all contexts. The \mid
command provides the correct spacing for “middle” separators.
Use \mid
for conditional expressions and set notation.
P(A \mid B) = \frac{P(A \cap B)}{P(B)}
Use \bigm|
for Adjustable Size:
P\bigl(A \bigm| B\bigr)
Define Custom Commands:
\newcommand{\given}{\mid}
P(A \given B)
For complex expressions, use \left
and \right
with \middle|
:
P\left( A \,\middle|\, B \right)
This ensures that the size of the delimiters adjusts appropriately to the content.
Numbers and their associated units or symbols can be separated across lines if LaTeX inserts a line break between them, leading to awkward and confusing formatting.
The distance is 10 km.
See Figure 1 for details.
If a line break occurs after “10” or “Figure,” the unit or figure number is separated.
By default, LaTeX treats spaces as possible breakpoints. To keep numbers and units together, non-breaking spaces are needed.
Use a tilde ~
to create a non-breaking space between the number and the unit or reference.
The distance is 10~km.
See Figure~1 for details.
Use \nobreakspace
:
The distance is 10\nobreakspace km.
Employ the siunitx
Package for Units:
\usepackage{siunitx}
The distance is \SI{10}{\kilo\metre}.
For dates and other connected phrases, use non-breaking spaces:
On April~15, we observed...
Refer to Equation~(2).
This ensures that connected information stays together, enhancing readability.
\DeclarePairedDelimiter
Manually sizing delimiters using \left
and \right
can lead to inconsistent formatting and excessive whitespace.
\left( \frac{a}{b} \right) + \left( \frac{c}{d} \right)
Using \left
and \right
forces LaTeX to size delimiters based on the content, which may not always be visually optimal.
Use the \DeclarePairedDelimiter
command from the mathtools
package to define paired delimiters with flexible sizing.
\usepackage{mathtools}
\DeclarePairedDelimiter{\paren}{(}{)}
\[
\paren*{\frac{a}{b}} + \paren*{\frac{c}{d}}
\]
*
in \paren*{}
automatically adjusts the size of the delimiters.Specify Delimiter Size Manually:
\[
\paren[\bigg]{\frac{a}{b}} + \paren[\Big]{\frac{c}{d}}
\]
Use \mleft
and \mright
for Better Spacing:
\[
\mleft( \frac{a}{b} \mright) + \mleft( \frac{c}{d} \mright)
\]
Define additional paired delimiters for brackets, braces, or absolute values:
\DeclarePairedDelimiter{\bracket}{[}{]}
\DeclarePairedDelimiter{\abs}{\lvert}{\rvert}
\[
\abs*{\frac{a}{b}}
\]
This approach ensures consistent delimiter sizing throughout your document.
Redefining existing LaTeX commands can cause unexpected behavior and conflicts, leading to errors or loss of functionality.
\newcommand{\table}{This is my table.}
By redefining \table
, you overwrite the existing command, which can interfere with LaTeX’s internal operations or other packages.
Use unique names for custom commands, preferably with a prefix.
\newcommand{\mytable}{This is my table.}
Check Command Existence Before Defining:
\providecommand{\mycommand}{...}
Use Package-Specific Namespaces: Some packages allow defining commands within their own namespace.
Develop a naming convention for your custom commands, such as prefixing them with your initials or project abbreviation, e.g., \ABsection
.
LaTeX error messages can be cryptic, making identifying and fixing issues challenging.
An error message like:
! Missing $ inserted.
This error often occurs when a math-mode-only symbol is used outside of math mode or when a $
is missing.
$...$
or \[...\]
.Consult online resources like TeX Stack Exchange, where similar errors are discussed. Copy the error message into the search bar to find potential solutions.
Not properly structuring large documents leads to slow compilation times and difficulty in navigation.
Writing an entire thesis in a single .tex
file.
Large documents become unwieldy when not broken into manageable parts.
\include
and \input
Commands: Split the document into multiple files.% Main document (main.tex)
\documentclass{book}
\begin{document}
\tableofcontents
\include{chapters/introduction}
\include{chapters/methodology}
\include{chapters/results}
\end{document}
Use the subfiles
Package: Allows individual compilation of chapters.
\usepackage{subfiles}
Use \includeonly{}
to compile only specific chapters, speeding up the compilation process during editing.
Manually formatting citations and bibliographies is time-consuming and prone to errors.
Manually typing bibliography entries at the end of the document.
Manual management is inefficient and does not scale well with many references.
Use bibliography management packages like biblatex
with biber
.
\usepackage[
backend=biber,
style=authoryear,
]{biblatex}
\addbibresource{references.bib}
As discussed in \cite{Doe2020}, the results are significant.
...
\printbibliography
.bib
files.Customize citation styles extensively with biblatex
options, ensuring compliance with journal requirements.
\newcommand
and \renewcommand
Using \newcommand
to redefine existing commands or \renewcommand
to define new commands leads to errors.
Command \foo already defined
.\newcommand{\section}[1]{\textbf{#1}}
Using \newcommand
on an existing command (\section
) results in an error because it is already defined.
Use \renewcommand
to redefine existing commands.
\renewcommand{\section}[1]{\textbf{#1}}
When redefining commands, consider the impact on document structure and package compatibility.