[Tex/LaTex] Passing options to the newenvironment


I have a GrayBox environment defined as follows.

It is used \begin{GrayBox}...\end{GrayBox} or \begin{GrayBox}[\textwidth]...\end{GrayBox}, that is, it can pass optional parameter to the environment.

I guess #1 is the setup for default value, and #2 is for setup for the value given.


How is #2 possible? I mean, is it LaTeX's rule that if #1 is not given, the default value in [] is used instead? Is there any reference about this? Is the same technique can be applied to \newcommand?

\newenvironment{GrayBox}[1][\dimexpr\textwidth-4.5ex]% **** #1
   {\setlength{\RoundedBoxWidth}{\dimexpr#1} **** #2
   {   \end{minipage}
       \draw node[draw=black,fill=black!10,rounded corners,%
             inner sep=2ex,text width=\RoundedBoxWidth]%

Best Answer

It is LaTeX's rule that if the optional argument is not present, then #1 takes on the default value. That is,

\newenvironment{hello}[1][world]{\noindent Hello #1, }{Bye now!\\}
    nice to meet you.
    glad you could make it.

will produce

Hello world, nice to meet you. Bye now!
Hello Bob, glad you could make it. Bye now!

as its output. The same is true for commands defined with optional parameters, as in

\newcommand{\hi}[1][world!]{\noindent Hello #1}
  \hi \\

which results in the output

Hello world!
Hello Bob

Related Question