[Tex/LaTex] key-value syntax in package options

key-valuepackage-optionspackage-writing

I want to create a style file capturing my layout for theorem environments. In particular, I would like to pass an option to the package specifying the level of the theorem counter. So here is a minimal working example:

The style file:

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mytheorem}

\RequirePackage{amsthm}
\newcommand{\level}{}

\DeclareOption{section}{\renewcommand{\level}{section}}
\DeclareOption{chapter}{\renewcommand{\level}{chapter}}
\ProcessOptions\relax

\theoremstyle{plain}
\newtheorem{theorem}{Theorem}[\level]
\newtheorem{corollary}[\level]{Corollary}

The document:

\documentclass{book}
\usepackage[section]{mytheorem}
\begin{document}
    \begin{corollary}
        Inhalt...
    \end{corollary}
\end{document}

However it would be nice to specify the option via a key-value syntax like so:

\usepackage[theoremlevel=section]{mytheorem}

How can this be done?

Best Answer

With xkeyval it is very simple to provide key values to packages, using \DeclareOptionX and \ProcessOptionsX, parsing the keys and doing the relevant options/redefinitions.

In order to preset some default values, use \ExecuteOptionsX{theoremlevel=section}, for example.

\DeclareOptionsX* is meant for processing unknown options.

Package file:

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{mytheorem}

\RequirePackage{amsthm}
\RequirePackage{xkeyval}

\newcommand{\level}{}

\DeclareOptionX{theoremlevel}{\renewcommand{\level}{#1}}
\DeclareOptionX*{\PackageWarning{mytheorem}{`\CurrentOption' ignored}}% For unknown options
\ExecuteOptionsX{theoremlevel=section}% Preset keys, 'section' being the default here

\ProcessOptionsX\relax

\theoremstyle{plain}
\newtheorem{theorem}{Theorem}[\level]
\newtheorem{corollary}[\level]{Corollary}

\endinput

Driver file:

\documentclass{book}
\usepackage[theoremlevel=chapter,foo]{mytheorem}% foo should provide a warning!
\begin{document}
    \begin{corollary}
        Inhalt...
    \end{corollary}
\end{document}
Related Question