I'm trying to create a package with some options. However, whenever I declare options and load other packages, I receive the following error:
LaTeX Error:
\RequirePackage
or\LoadClass
in Options Section.
What is going on here and/or how do I declare package options and load packages?
Here is a minimal example replicating the problem:
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{mystyle.sty}
\newcommand{\mycmd}{new}% Define some command
\DeclareOption{change}{\renewcommand{\mycmd}{renew}}% Package option `change` updates \mycmd
\RequirePackage{amsmath}% Load amsmath
\end{filecontents*}
\usepackage{mystyle}
\begin{document}
\mycmd% This should be "new"
\end{document}
Best Answer
At the moment you use
\DeclareOption
, your style file is divided into three parts:Pre-options Section (above first
\DeclareOption
);Options Section (between first
\DeclareOption
and\ProcessOptions
); andPost-options Section (after
\ProcessOptions
).Whatever is contained within the pre-options section has already been processed. So, the only problem arises with content beyond this point.
Since the possibility exists that you may want to conditionally load a package (or class) based on some option, and the fact that once a package (or class) is loaded you can't "undo" the action,
\RequirePackage
(also\usepackage
) is made a invoke an error if used within the options section. Here's an example of how one may decide to load a package conditionally:You'll have to
\ProcessOptions
before\RequirePackage
(in the above case, outside the if-condition), for the above code to be successful. In general, issue\ProcessOptions
in order to put yourself in the post-options section before you can load any more packages (or classes).In the specific example, the following change to
mystyle.sty
should suffice: