LaTeX style (.sty) files

Posted: 27th June 2014 by Tim in LaTeX
Tags: , , , , , ,

When writing LaTeX documents, you may find yourself copying and pasting some common settings such as margins, fonts and paragraph indentation. This is not only tedious, it can be a real headache if you’re writing multiple documents that you want to look the same. To solve this problem, you can use a style (.sty) file.

A style file uses the same syntax as a LaTeX file, but uses the .sty suffix. To use this file in your LaTeX document, load it using the \usepackage{<filename_without_sty_suffix>} syntax.

Consider the following two files:

timstyle.sty

% timstyle.sty
% This file contains common document settings

% Page margins (2cm wider, 2cm longer)
\addtolength{\textwidth}{2cm}
\addtolength{\hoffset}{-1cm}
\addtolength{\textheight}{2cm}
\addtolength{\voffset}{-1cm}

% Font (Times New Roman)
\usepackage{times}

% No paragraph indentation
\setlength{\parindent}{0in}

example.tex

\documentclass[11pt, a4paper]{article}
\usepackage{timstyle} % note: no .sty suffix here
\begin{document}
Hello World! This is the first paragraph in the document.
The paragraph is not very long, but it spans multiple lines.
As you can see, the first line of the paragraph is not indented.\\

This is the second paragraph. Look --- still no indentation!
\end{document}

The code above will produce this document. As you can see, the margin, font and paragraph indentation settings are in timstyle.sty, which simplifies the example.tex file. The style file can now be reused in other files too.