2

Context: I want to create a custom environment. For that, I use the command \newenvironment{<environment-name>}{<before>}{<after>}. However, in my case, <after> starts with }, so LaTeX thinks this bracket closes the definition of <after>...

Question: How to create a new environment where <after> starts with }?


MWE: In the example below, I define an environment that creates a tikzpicture and a node around the content thereof. (I know an easy workaround would be to use newcommand instead, but my real case requires an environment.)

\documentclass{article}
    \usepackage{tikz}

    \newenvironment{myenvironment}{%
        \begin{tikzpicture}
            \node[draw, red]{
    }{%
            };
        \end{tikzpicture}%
    }
\begin{document}
    \begin{myenvironment}
        Foo bar
    \end{myenvironment}
\end{document}

Tested non-working solutions:

  • I have tried \newenvironment{<environment-name>}{<before>}{\null<after>} but it doesn't work.
  • I have also tried to change { and } by \bgroup and \egroup repectively - both for the environment definition (\newenvironment{<environment-name>} \bgoup <before>\egroup\bgroup <after>\egroup), or in the node definition (... \node[draw, red]\bgroup}{\egroup; ...). No success.
2

I would use environ.

\documentclass{article}
\usepackage{tikz}
\usepackage{environ}
\NewEnviron{myenvironment}{%
  \tikz{\node[draw, red]{\BODY};}%
}
\begin{document}
\begin{myenvironment}
  Foo bar
\end{myenvironment}
\end{document}
  • The braces around the argument of \node are true “argument-delimiters”, aren’t they? – GuM May 7 '17 at 1:10
  • @GustavoMezzetti Er .... Why? – cfr May 7 '17 at 1:19
  • @GustavoMezzetti I just know this is how, say, the forest environment is defined and, indeed, how prooftree is defined. I figured it would work here, too. (I don't mean I didn't test it - I did test it and it did work.) – cfr May 7 '17 at 1:21
  • Oh, it will work, that’s certain. But, as you probably know, this approach is highly inefficient from TeX’s point of view. So, I was wondering whether \node absorbs its {...} argument wholly before processing it (as I would expect), or it processes it in the same way as, say, \hbox{...} processes its “argument”. But the second case is actually ruled out, for otherwise \newenvironment{myenvironment}{... \node[...] \bgroup}{\egroup ...} would have worked. – GuM May 7 '17 at 1:32
  • @GustavoMezzetti I didn't know it was inefficient. Can't say I had thought about it. Certainly I've thought about prooftrees being slow, but that is mostly due to forest and pgf being slow. I just knew it was safe - or thought I did, until I wondered if you were suggesting not. – cfr May 7 '17 at 1:36

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.