Typevia
Advanced Topics

Introduction to LaTeX Packages

As you become more proficient with LaTeX, you will find yourself reusing the same set of commands, preamble settings, and formatting rules across multiple documents. Copying and pasting a 50-line preamble into every new .tex file is not only tedious but also prone to errors. If you decide to change a specific setting, you would have to update every single file manually.

This is where LaTeX packages come in. A package is essentially a separate file (with a .sty extension) that contains a collection of LaTeX commands and settings. By creating your own package, you can:

  • Modularize your work: Keep your main document clean and focused on content.
  • Ensure consistency: Use the same styling across your thesis, lab reports, and CV.
  • Share code: Easily give your custom tools to colleagues or students.

In this guide, we will walk through the process of creating your first .sty file and implementing advanced features like package options.

The Structure of a .sty File

A LaTeX package is a simple text file, but it must follow a specific structure to be recognized correctly by the LaTeX engine. Unlike a standard document, it does not use \documentclass or the document environment. Instead, it uses specialized identification commands.

Essential Identification Commands

Every package should start with these two commands:

  1. \NeedsTeXFormat{LaTeX2e}: This tells the compiler which version of LaTeX is required to run this package.
  2. \ProvidesPackage{packagename}[YYYY/MM/DD v1.0 Brief Description]: This identifies the package to the system. The name must match the filename (e.g., if your file is mystyle.sty, the name here must be mystyle).

The Body

After the identification, you can include any standard LaTeX code:

  • Loading other packages using \RequirePackage (instead of \usepackage).
  • Defining new commands using \newcommand.
  • Setting page margins, fonts, or colors.

Note: Inside a .sty file, the @ character is treated as a letter. This allows package authors to create "internal" commands (like \my@internal@cmd) that users cannot accidentally overwrite in their main document.


Creating Your First Package

Let's create a practical example. Imagine you are a math student and you frequently use specific formatting for your homework. We will create a package named mathhomework.

Step 1: Create the .sty file

Create a file named mathhomework.sty in the same folder as your .tex file and add the following:

% Identification
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mathhomework}[2023/10/27 My Custom Math Style]

% Requirements
\RequirePackage{amsmath}
\RequirePackage{amsfonts}
\RequirePackage{xcolor}

% Custom Commands
\newcommand{\R}{\mathbb{R}}
\newcommand{\N}{\mathbb{N}}
\newcommand{\complex}{\mathbb{C}}

% A command for "Note" boxes
\newcommand{\hwnote}[1]{%
    \par\noindent\textcolor{blue}{\textbf{Note:}} \textit{#1}\par
}

% Set a default margin behavior (optional)
\RequirePackage[margin=1in]{geometry}

Step 2: Use the package in a document

Now, create a file named main.tex in the same directory. You can load your custom package just like graphicx or hyperref.

\documentclass{article}
\usepackage{mathhomework}

\begin{document}

Let $x \in \R$ be a real number. We know that the set of natural numbers $\N$ is a subset of $\R$.

\hwnote{Remember to show all steps in the proof.}

\end{document}

Adding Package Options

Sometimes you want your package to behave differently based on user input. For example, you might want a "dark mode" or a "compact" version of your styles. We handle this using "options."

To add options, we use \DeclareOption{name}{code} and \ProcessOptions\relax.

Example: A Package with a "Draft" Option

Let's modify a style package to include a "serif" option that changes the font.

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{customfonts}[2023/10/27 Font Switcher]

% Define a toggle for our option
\newif\if@usecustomserif \@usecustomseriffalse

% Declare the option
\DeclareOption{serif}{
    \@usecustomseriftrue
}

% Handle unknown options
\DeclareOption*{
    \PackageWarning{customfonts}{Unknown option ‘\CurrentOption’}
}

% Execute the options
\ProcessOptions\relax

% Apply logic based on options
\if@usecustomserif
    \RequirePackage{charter} % Use Charter font if serif option is passed
\else
    \RequirePackage{helvet}  % Use Helvetica otherwise
    \renewcommand{\familydefault}{\sfdefault}
\fi

To use this, the user would write \usepackage[serif]{customfonts} in their LaTeX document.


Installation and File Location

Where should you save your .sty file? There are two main approaches:

  1. Local (Project-specific): Save the .sty file in the same folder as your .tex file. LaTeX always looks in the current directory first. This is best for one-off projects or when sharing a project with a collaborator.
  2. Global (System-wide): If you want to use the package for every document you create on your computer, you should place it in your local texmf tree.
    • Windows (MikTeX): Usually C:\Users\Name\AppData\Local\Programs\MiKTeX\tex\latex\custom\
    • Mac/Linux (TeX Live): ~/texmf/tex/latex/common/

Note: After moving a file to the global texmf tree, you must run the command texhash (for TeX Live) or use the MikTeX Console to "Refresh FNDB" so the system can find the new file.


Best Practices and Common Pitfalls

To create high-quality, professional packages, keep these tips in mind:

1. Unique Command Names

If you name a command \title, you will break the standard LaTeX title functionality. Always prefix your commands if they are specific to your package (e.g., \mhHomeworkTitle instead of \Title).

2. Don't Over-automate

A package should provide tools, not take over the document. Avoid including \begin{document} or forcing specific document classes inside a .sty file.

3. Use \RequirePackage

Never use \usepackage inside a .sty file. While it often works, \RequirePackage is specifically designed for use in packages and handles dependencies and versioning more robustly.

4. Documentation is Key

Even if you are the only user, comment your code. Use % to explain why you are loading a specific package or what a complex macro does.

Common Mistake: Forgetting \relax

When using \ProcessOptions, always add \relax afterward. This prevents LaTeX from accidentally grabbing following characters and trying to interpret them as part of the option processing.

\ProcessOptions\relax

Common Mistake: Filename Mismatch

If your file is named MyStyles.sty, your code must say \ProvidesPackage{MyStyles}. LaTeX is case-sensitive on most systems, so mystyles will not match MyStyles.