1

I turned my most used packages and macros and environments into a package (and defined options for some). There is one thing I could not figure out. Say I have this environment definition in my custom .sty file:

\newenvironment{myenvironment}
 {\par\addvspace{3ex}%
 \nopagebreak\noindent\hspace{0.5in}}
 {\par\addvspace{3ex}%
 \ignorespacesafterend}

Now, when I load the package, I'd like to have the ability to customize the options of this environment, such as (say):

\usepackage[myenvironment hspace=1in]{mydefaultpreamble}

How do I do that?

  • 1
    the standard option handler never takes values, however there are several extended versions eg the kvoptions package (based on the code developed for hyperref) – David Carlisle Nov 24 '16 at 8:57
4

Here is an example with the kvoptions package.

\RequirePackage{kvoptions}
\SetupKeyvalOptions {}

\ProvidesPackage{mydefaultpreamble} 
\DeclareStringOption[0.5in]{myenvironmenthspace}

\newenvironment{myenvironment}
 {\par\addvspace{3ex}%
 \nopagebreak\noindent\hspace{\mydefaultpreamble@myenvironmenthspace}}
 {\par\addvspace{3ex}%
 \ignorespacesafterend}

\ProcessKeyvalOptions{mydefaultpreamble}

And the use it

\documentclass{article}

\usepackage[myenvironment hspace=5cm]{mydefaultpreamble}

\begin{document}

\begin{myenvironment}
  Some text
\end{myenvironment}

\setkeys{mydefaultpreamble}{myenvironmenthspace=2cm}

\begin{myenvironment}
  Another text
\end{myenvironment}

\end{document}

As you see, the key must be defined without spaces, but it can be used with spaces, although I would not recommend that. However in \setkeys it must be used without spaces.

  • is \ProvidesPackage{mydefaultpreamble} needed every time I declare an option? – blackened Nov 25 '16 at 19:15
  • 1
    \ProvidesPackage{mydefaultpreamble} isn't strictly necessary. It is a nicety to tell what package it is, and it is only necessary once in the package. But it is good to do it, and you can also add a version number to it. – Piet van Oostrum Nov 25 '16 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.