Typevia
Advanced Topics

Understanding Document Classes

In LaTeX, the document class defines the overall structure and layout of your document. Most users begin by using standard classes like article, report, or book. However, as you develop a specific style for your CV, your university assignments, or a corporate newsletter, you might find yourself copying and pasting a long preamble from one document to another.

This is where Custom Document Classes come in. By creating a .cls file, you move the "styling" logic out of your content file and into a separate, reusable file.

Why Create a Custom Class?

  1. Consistency: Ensure all your documents (e.g., every homework assignment) look identical.
  2. Cleanliness: Your main .tex file will contain only content, making it easier to read.
  3. Portability: You can share your .cls file with colleagues or students so they can follow the same formatting rules effortlessly.
  4. Efficiency: Global changes (like changing a font or margin size) only need to be made in one file.

The Basic Structure of a .cls File

A document class is a plain text file saved with the .cls extension. It must contain specific "boilerplate" commands at the top to tell LaTeX how to handle it.

Required Commands

  • \NeedsTeXFormat{LaTeX2e}: Specifies the version of LaTeX the class is designed for.
  • \ProvidesClass{classname}[Date Description]: Identifies the class name and provides versioning information.

Example 1: A Minimal Class File

Create a file named mybasicclass.cls:

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{mybasicclass}[2023/10/27 My Custom LaTeX Class]

% Inherit from an existing class
\LoadClass{article}

% Customizations go here
\RequirePackage[utf8]{inputenc}
\RequirePackage[T1]{fontenc}

To use this, your .tex file would simply start with \documentclass{mybasicclass}.

Note: The filename must match the first argument of \ProvidesClass exactly. If your file is myclass.cls, the command must be \ProvidesClass{myclass}.


Inheriting and Modifying Classes

Most custom classes are not written from scratch. Instead, they "inherit" functionality from standard classes like article or report using the \LoadClass command.

Handling Options

If you want your custom class to accept options (like 12pt or a4paper) and pass them to the underlying class, you need to handle "options."

  1. \DeclareOption{optionname}{code}: Defines what happens when a specific option is called.
  2. \ProcessOptions\relax: Tells LaTeX to execute the code for the selected options.
  3. \LoadClass: Loads the base class.

Example 2: Passing Options to the Base Class

If you want your class to support everything the article class does, use \DeclareOption*.

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{assignment}[2023/10/27 Assignment Class]

% Pass all unknown options to the 'article' class
\DeclareOption*{%
  \PassOptionsToClass{\CurrentOption}{article}%
}
\ProcessOptions\relax
\LoadClass{article}

% Set default margins
\RequirePackage[margin=1in]{geometry}

Defining Custom Commands and Layouts

One of the main reasons to build a class is to automate the layout of specific elements, such as title pages or headers.

Inside a class file, you should use \RequirePackage instead of \usepackage. This ensures that dependencies are loaded correctly before the document begins.

Example 3: Creating a Custom Header

In this example, we use the fancyhdr package to define a consistent header for every page within the class file.

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{companyreport}[2023/10/27 Corporate Report Class]
\LoadClass{report}

\RequirePackage{fancyhdr}
\RequirePackage{graphicx}

% Setup page style
\pagestyle{fancy}
\fancyhf{}
\rhead{Confidential - Project X}
\lhead{\thepage}
\rfoot{Draft Version 1.0}

% Custom Command for a subtitle
\newcommand{\subtitle}[1]{\def\@subtitle{#1}}

Practical Project: A Custom Assignment Class

Let's build a functional class for university assignments. This class will automatically set the margins, define a custom title format, and create a special "Problem" environment.

The Class File: uni-hw.cls

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{uni-hw}[2023/10/27 University Homework Class]

\LoadClass[11pt]{article}

% Packages
\RequirePackage[margin=1.2in]{geometry}
\RequirePackage{amsmath, amssymb}
\RequirePackage{tcolorbox} % For styled boxes

% Custom Title Command
\renewcommand{\maketitle}{
    \begin{center}
        {\LARGE \bfseries \@title} \\
        \vspace{2mm}
        {\large \@author} \\
        \vspace{1mm}
        {\itshape \@date}
        \hrulefill
    \end{center}
    \vspace{1cm}
}

% Custom Environment for Problems
\newenvironment{problem}[1]{%
    \begin{tcolorbox}[colback=gray!5,colframe=blue!40!black,title=Problem #1]
}{%
    \end{tcolorbox}\vspace{0.5cm}
}

The Document File: main.tex

\documentclass{uni-hw}

\title{Physics 101: Problem Set 1}
\author{Jane Doe}
\date{October 27, 2023}

\begin{document}
\maketitle

\begin{problem}{1}
Calculate the velocity of an object falling from 10 meters, ignoring air resistance.
\end{problem}

\noindent \textbf{Solution:} Using the formula $v = \sqrt{2gh}$...

\end{document}

Best Practices and Common Pitfalls

1. File Placement

For LaTeX to find your .cls file, it must be in the same folder as your .tex file. If you want to use it globally (in any project), you must place it in your local texmf tree. On most systems, this is a more advanced step, so keeping it in the project folder is recommended for beginners.

2. Use \RequirePackage

Never use \usepackage inside a .cls file. While it might work occasionally, \RequirePackage is designed specifically for class and package files to prevent conflicts and ensure correct loading order.

3. Avoid Hard-Coding Content

The class file should contain formatting, not content. For example, don't type your actual name in the class file; instead, define a command (like \author) that allows the user to input their name in the .tex file.

4. The @ Symbol

You may notice commands like \@author or \@title in professional class files. In LaTeX, the @ symbol is used for "internal" commands. In a .cls file, you can use @ freely. However, in a standard .tex file, you cannot use these commands unless you wrap them in \makeatletter and \makeatother.

5. Error Handling

If your class isn't loading, check the log file. The most common error is a mismatch between the filename and the name inside \ProvidesClass.

Tip: If you are building a complex class, start by putting your code in the preamble of a .tex file. Once it works perfectly, move it into a .cls file. This makes debugging much faster!