5

I want to define an environment that read its content before processing (like \newEnviron from the package environ) but also that allows key-value parameters (like \newkeyenvironment from the package keycommand that I usually use).

How should I do?

Werner
  • 603,163
Loic Rosnay
  • 8,167

2 Answers2

5

There's nothing special: assuming you've defined a bar family of keys

\NewEnviron{foo}[1]{%
  \setkeys{bar}{#1}%
  do something with \BODY
}

or

\NewEnviron{foo}[1][]{%
  \setkeys{bar}{#1}%
  do something with \BODY
}

will allow the syntax

\begin{foo}{key1=value1,key2=value2}
text
\end{foo}

or

\begin{foo}[key1=value1,key2=value2]
text
\end{foo}

respectively. Which one to prefer depends on many factors: if the user has to supply at least a key-value pair, then the first form is recommended.

I've used \setkeys, as I don't know how keycommand works (it should be very similar, anyway).

egreg
  • 1,121,712
  • ok, thanks, i had never used \setkeys, because i found the syntax of keycommand easier. So, I have to read how to use \setkeys. From which package is it ? – Loic Rosnay Mar 13 '12 at 10:14
  • 1
    keycommand loads xkeyval, which is an extension of keyval. I recommend looking at the documentation of keyval which is quite neat about defining and setting keys. – egreg Mar 13 '12 at 10:22
4

Here is an option with keyval and environ:

enter image description here

\documentclass{article}
\usepackage{keyval}% http://ctan.org/pkg/keyval
\usepackage{environ}% http://ctan.org/pkg/environ
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\makeatletter
\define@key{mykeys}{font}{\def\envfont{#1}}%
\makeatother
\NewEnviron{myenv}[1][]{%
  \setkeys{mykeys}{font=\normalfont,#1}% Set default and updated keys
  \envfont\BODY% Set contents in font \envfont
}
\begin{document}
\lipsum[1]
\begin{myenv}[font=\bfseries\itshape]
\lipsum[1]
\end{myenv}
\end{document}

The above example sets the font of the environment myenv using a key-value given by font. The key-value is stored in the family mykeys with font=\normalfont being the default. For more on setting key-value pairs, see How to create a command with key values?

lipsum provides Lorem Ipsum-style dummy text.

Werner
  • 603,163
  • thanks a lot. By the way, is there a way to define a key, which would act as a boolean swithc, but which one could call with [switch] instead of [switch =true] ? – Loic Rosnay Mar 13 '12 at 12:00