Mastering LaTeX

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.


Introduction

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.


Simple Mistakes

1. Misplaced or Missing Braces {}

The Issue

LaTeX uses braces {} to group content and define the scope of commands. Missing or misplacing braces can lead to compilation errors or unintended formatting.

Symptoms

Example of the Mistake

\textbf{This is bold text.

Explanation

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.

Solution

Ensure every opening brace { has a corresponding closing brace }.

Corrected Code

\textbf{This is bold text.}

Alternative Solutions

Out-of-the-Box Tip

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.


2. Undefined Control Sequences

The Issue

Using commands that LaTeX does not recognize, often due to typos or missing packages, leads to Undefined control sequence errors.

Symptoms

Example of the Mistake

\begin{document}
\includegraphics{image.png}
\end{document}

Explanation

The \includegraphics{} command is provided by the graphicx package. Without including this package in the preamble, LaTeX does not recognize the command.

Solution

Include the necessary package in the preamble.

Corrected Code

\documentclass{article}
\usepackage{graphicx}

\begin{document}
\includegraphics{image.png}
\end{document}

Alternative Solutions

Out-of-the-Box Tip

Use the \RequirePackage{} directive in custom class or package files to ensure necessary packages are always loaded, especially when collaborating with others.


3. Ignoring Special Characters

The Issue

Certain characters have special meanings in LaTeX and cannot be used directly in text. These include #, %, $, &, _, {, }, ^, ~, and \.

Symptoms

Example of the Mistake

The cost is $100 & tax included.

Explanation

The & character is used for alignment in tables and arrays. Using it outside of these environments without escaping causes an error.

Solution

Escape special characters by prefixing them with a backslash \.

Corrected Code

The cost is \$100 \& tax included.

Alternative Solutions

Out-of-the-Box Tip

Use the listings or minted package to handle special characters automatically and provide syntax highlighting for code listings.


4. Overfull and Underfull Boxes

The Issue

Overfull or underfull boxes occur when LaTeX cannot properly fit text within the specified margins, leading to too wide or too narrow lines.

Symptoms

Example of the Mistake

This long line of text will likely cause an overfull hbox warning because it cannot be broken properly.

Explanation

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.

Solution

Corrected Code

\usepackage{microtype}

This long line of text will likely cause an over\-full hbox warning because it cannot be broken properly.

Alternative Solutions

Out-of-the-Box Tip

Set \emergencystretch=3em to allow LaTeX to adjust spacing in emergency situations without affecting overall formatting.


5. Incorrect Figure and Table Placement

The Issue

Figures and tables (floats) only sometimes appear where you expect them due to LaTeX’s float placement algorithm and incorrect placement specifiers.

Symptoms

Example of the Mistake

\begin{figure}
  \includegraphics{image.png}
  \caption{An example image}
  \label{fig:example}
\end{figure}

No placement specifier is provided, so LaTeX defaults to [tbp].

Explanation

LaTeX places floats according to allowed positions:

LaTeX uses its algorithm without explicit instructions, which may not align with your expectations.

Solution

Specify float placement options to guide LaTeX.

Corrected Code

\begin{figure}[htbp]
  \centering
  \includegraphics{image.png}
  \caption{An example image}
  \label{fig:example}
\end{figure}

Detailed Explanation of [htbp] vs. [htb]

Alternative Solutions

Out-of-the-Box Tip

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

6. Incorrect Use of Math Mode

The Issue

Failing to correctly enter or exit math mode results in incorrect formatting and errors.

Symptoms

Example of the Mistake

The solution to ax + b = 0 is x = -b/a.

Explanation

Mathematical expressions need to be enclosed in $...$ or \[...\] to be typeset correctly.

Solution

Ensure all mathematical content is within math mode delimiters.

Corrected Code

The solution to $ax + b = 0$ is $x = -b/a$.

Alternative Solutions

Out-of-the-Box Tip

Use the amsmath package for enhanced mathematical typesetting capabilities, providing environments like align, gather, and multline.


7. Improper Use of \label and \ref Commands

The Issue

Incorrectly placing \label commands or not using \ref and \pageref properly leads to broken or incorrect cross-references.

Symptoms

Example of the Mistake

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

Explanation

To correctly reference the number, the \label command should come immediately after the counter-stepping command (like \section, \caption, etc.).

Solution

Place \label immediately after the sectioning or captioning command.

Corrected Code

\section{Introduction}\label{sec:intro}

As discussed in Section \ref{sec:intro}, ...

Alternative Solutions

Out-of-the-Box Tip

Consider using the cleveref package to automate reference formatting and reduce errors for complex documents.


8. Not Loading Necessary Packages

The Issue

Neglecting to include packages that provide essential commands or functionalities results in errors or missing features.

Symptoms

Example of the Mistake

Using \mathbb{R} without including the amssymb package.

Let $x \in \mathbb{R}$.

Explanation

The \mathbb{} command is provided by the amssymb package.

Solution

Include the necessary package in the preamble.

Corrected Code

\usepackage{amssymb}

Let $x \in \mathbb{R}$.

Alternative Solutions

Out-of-the-Box Tip

Create a personal package or class file that includes frequently used packages for consistency across documents.


9. Improper Font Encoding

The Issue

Using characters that are not supported by the default font encoding leads to errors or missing characters.

Symptoms

Example of the Mistake

Using accented characters without specifying the proper font encoding.

El Niño phenomenon affects climate patterns.

Explanation

By default, LaTeX uses the OT1 font encoding, which does not support accented characters directly.

Solution

Include the fontenc and inputenc packages.

Corrected Code

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

El Niño phenomenon affects climate patterns.

Alternative Solutions

Out-of-the-Box Tip

Set the document to use modern fonts and encoding from the start to avoid encoding issues.


10. Forgetting to Save Files with the Correct Encoding

The Issue

Saving files in the wrong encoding causes LaTeX to misinterpret special characters.

Symptoms

Example of the Mistake

Writing the document with UTF-8 characters but saving it in ANSI encoding.

Explanation

LaTeX reads the file according to the specified encoding. Mismatches between file encoding and declared encoding lead to errors.

Solution

Corrected Code

\usepackage[utf8]{inputenc}

Alternative Solutions

Out-of-the-Box Tip

Ensure all team members use the same encoding settings to prevent conflicts when collaborating.


Advanced Mistakes

1. Misuse of Math Operators (\sin, \log, etc.)

The Issue

Not using the proper commands for mathematical operators leads to incorrect formatting, such as operators appearing italicized like variables.

Symptoms

Example of the Mistake

Let $y = sin(x) + log(x)$.

Explanation

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.

Solution

Use LaTeX’s built-in commands for standard mathematical operators.

Corrected Code

Let $y = \sin(x) + \log(x)$.

Alternative Solutions

Out-of-the-Box Tip

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.


2. Inadequate Spacing in Math Mode

The Issue

LaTeX may not automatically provide appropriate spacing in mathematical expressions, especially around certain symbols or complex equations.

Symptoms

Example of the Mistake

If $x>y$, then $f(x)=g(y)$.

Explanation

LaTeX does not always insert adequate spacing around relational operators (=, <, >) and between function names and variables.

Solution

Use spacing commands in math mode to adjust space as needed.

Corrected Code

If $x > y$, then $f(x) = g(y)$.

Spacing Commands

Alternative Solutions

Out-of-the-Box Tip

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.


3. Misuse of \mid vs. | in Math Mode

The Issue

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

Symptoms

Example of the Mistake

P(A|B) = \frac{P(A \cap B)}{P(B)}

Explanation

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.

Solution

Use \mid for conditional expressions and set notation.

Corrected Code

P(A \mid B) = \frac{P(A \cap B)}{P(B)}

Alternative Solutions

Out-of-the-Box Tip

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.


4. Not Using Non-Breaking Spaces for Units and Numbers

The Issue

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.

Symptoms

Example of the Mistake

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.

Explanation

By default, LaTeX treats spaces as possible breakpoints. To keep numbers and units together, non-breaking spaces are needed.

Solution

Use a tilde ~ to create a non-breaking space between the number and the unit or reference.

Corrected Code

The distance is 10~km.

See Figure~1 for details.

Alternative Solutions

Out-of-the-Box Tip

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.


5. Incorrect Use of \DeclarePairedDelimiter

The Issue

Manually sizing delimiters using \left and \right can lead to inconsistent formatting and excessive whitespace.

Symptoms

Example of the Mistake

\left( \frac{a}{b} \right) + \left( \frac{c}{d} \right)

Explanation

Using \left and \right forces LaTeX to size delimiters based on the content, which may not always be visually optimal.

Solution

Use the \DeclarePairedDelimiter command from the mathtools package to define paired delimiters with flexible sizing.

Corrected Code

\usepackage{mathtools}

\DeclarePairedDelimiter{\paren}{(}{)}

\[
\paren*{\frac{a}{b}} + \paren*{\frac{c}{d}}
\]

Alternative Solutions

Out-of-the-Box Tip

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.


6. Overloading Commands Unintentionally

The Issue

Redefining existing LaTeX commands can cause unexpected behavior and conflicts, leading to errors or loss of functionality.

Symptoms

Example of the Mistake

\newcommand{\table}{This is my table.}

Explanation

By redefining \table, you overwrite the existing command, which can interfere with LaTeX’s internal operations or other packages.

Solution

Use unique names for custom commands, preferably with a prefix.

Corrected Code

\newcommand{\mytable}{This is my table.}

Alternative Solutions

Out-of-the-Box Tip

Develop a naming convention for your custom commands, such as prefixing them with your initials or project abbreviation, e.g., \ABsection.


7. Not Understanding Error Messages

The Issue

LaTeX error messages can be cryptic, making identifying and fixing issues challenging.

Symptoms

Example of the Mistake

An error message like:

! Missing $ inserted.

Explanation

This error often occurs when a math-mode-only symbol is used outside of math mode or when a $ is missing.

Solution

Alternative Solutions

Out-of-the-Box Tip

Consult online resources like TeX Stack Exchange, where similar errors are discussed. Copy the error message into the search bar to find potential solutions.


8. Inefficient Handling of Large Documents

The Issue

Not properly structuring large documents leads to slow compilation times and difficulty in navigation.

Symptoms

Example of the Mistake

Writing an entire thesis in a single .tex file.

Explanation

Large documents become unwieldy when not broken into manageable parts.

Solution

Corrected Code

% Main document (main.tex)
\documentclass{book}
\begin{document}
\tableofcontents
\include{chapters/introduction}
\include{chapters/methodology}
\include{chapters/results}
\end{document}

Alternative Solutions

Out-of-the-Box Tip

Use \includeonly{} to compile only specific chapters, speeding up the compilation process during editing.


9. Neglecting the Use of Bibliography Tools

The Issue

Manually formatting citations and bibliographies is time-consuming and prone to errors.

Symptoms

Example of the Mistake

Manually typing bibliography entries at the end of the document.

Explanation

Manual management is inefficient and does not scale well with many references.

Solution

Use bibliography management packages like biblatex with biber.

Corrected Code

\usepackage[
  backend=biber,
  style=authoryear,
]{biblatex}
\addbibresource{references.bib}

As discussed in \cite{Doe2020}, the results are significant.

...

\printbibliography

Alternative Solutions

Out-of-the-Box Tip

Customize citation styles extensively with biblatex options, ensuring compliance with journal requirements.


10. Improper Use of \newcommand and \renewcommand

The Issue

Using \newcommand to redefine existing commands or \renewcommand to define new commands leads to errors.

Symptoms

Example of the Mistake

\newcommand{\section}[1]{\textbf{#1}}

Explanation

Using \newcommand on an existing command (\section) results in an error because it is already defined.

Solution

Use \renewcommand to redefine existing commands.

Corrected Code

\renewcommand{\section}[1]{\textbf{#1}}

Alternative Solutions

Out-of-the-Box Tip

When redefining commands, consider the impact on document structure and package compatibility.