Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
    
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] ? –  nicolas roy Mar 13 '12 at 12:00
add comment

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).

share|improve this answer
    
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 ? –  nicolas roy 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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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