[Tex/LaTex] Why use .sty files

best practicespackages

Why is it preferable to put inclusions of commonly used packages and user defined commands in a .sty file instead of putting them in an ordinary .tex file?

Best Answer

First of all: never use \include to load a file with personal definitions and packages to use.

The choice is thus between \input and \usepackage; for the first it's better to use the extension .tex for the file, for the second .sty is mandatory.

What are the pros of the latter solution? Many. For instance you can define options that can change the behavior of your macros or selectively load parts of it (see example below).

In a .sty file @ is assumed to be a letter, so no \makeatletter or \makeatother command is needed to access "private macros", which is often the case for complex macros.

If you don't need options nor access to private macros, loading your definitions and package with \input{mymacros} is exactly equivalent to \usepackage{mymacros} (provided that the file is mymacros.tex in the first case and mymacros.sty in the second one).

As noticed by Andrew Stacey, there is one more pro in using a .sty file: it won't be loaded twice, even if called twice in a document (maybe frome some other loaded file or package). This is important because \newcommand would raise errors on the second loading (and other definitions might lead to infinite loops).

Example: Suppose you have a macro that must change its behavior when the draft option is enabled in the \documentclass line; for instance it should have an argument that's emphasized in the text and is also written in the margin for draft copies.

\ProvidesPackage{mymacros}
\newif\if@myfiledraft
\DeclareOption{draft}{\@myfiledrafttrue}

\ProcessOptions\relax

\if@myfiledraft
  \newcommand{\myterm}[1]{\emph{#1}\marginpar{TERM: #1}}
\else
  \newcommand{\myterm}[1]{\emph{#1}}
\fi

\endinput

If a document does

\documentclass[draft]{article}
\usepackage{mymacros}

\begin{document}
\myterm{foo}
\end{document}

then "TERM: foo" will be written in the margin. If draft is removed, the same source will only emphasize "foo" in the text.

Related Question