2

I am trying to define an Environment myEnv s.t.

\begin{myEnv}
text1
\end{myEnv} text2}

expands to

\renewcommand{\myCommand}{
text1
} { text2}

The reason for the obviously unbalanced expression in the first code sample is the limited capability of LyX when it comes to defining macro parameters over multiple paragraphs - I have to cope with it at the moment. I've already tried

\NewEnviron{myEnv}{\expandafter\newcommand\csname myCommand \endcsname{\BODY} \bgroup}

however, this isn't working at all.

Edit: Based on egreg's answer, I give a minimal, non-working example:

\documentclass{scrartcl}
\usepackage{environ}

\newcommand{\myCommand}{}

\NewEnviron{myEnv}{%
  \expandafter\gdef\expandafter\myCommand\expandafter{\BODY}}

\begin{document}

\begin{myEnv}
text1
\end{myEnv} text2}

testing \myCommand testing

\end{document}

which gives the error

! Too many }'s.
l.13 \end{myEnv} text2}

The expected document output would be

text2 testing text1 testing
4
  • It's quite unclear what the role of {text1} and {text2} is, as apparently \myCommand is defined without arguments. Do you need to define a command or to use it?
    – egreg
    Commented Jan 4, 2012 at 9:52
  • Yes, \myCommand is defined without arguments - it is just a textual definition. I really need to define a command here; the code given above is really what I want to achieve. Note that this construction is only necessary to circumvent some nasty habits of LyX. Commented Jan 4, 2012 at 14:32
  • So, what \renewcommand{\myCommand}{<n>text1<n>}{ text2} (<n> stands for the new line) should mean? However, if you want to say \renewcommand{\myCommand}{<n>text1<n>}, you only need to say \renewcommand{\myCommand}{ text1 } (a new line there is exactly like a space).
    – egreg
    Commented Jan 4, 2012 at 14:37
  • Please observe that there is a whitespace before the { text2}. Thus the resulting code is \renewcommand{\myCommand}{<n>text1<n>} { text2}. This redefines myCommand and then simply emits text2 as normal text. text2 is not in any way part of the command definition! Commented Jan 4, 2012 at 14:46

1 Answer 1

7
\usepackage{environ}
\NewEnviron{myEnv}{%
  \expandafter\gdef\expandafter\myCommand\expandafter{\BODY}}

It's however quite difficult to understand what you need to achieve. If you want to write multiple paragraphs, you can simply say

\newcommand{\myCommand}{text of first paragraph\par text of second paragraph\par}

In order to cope with the bizarre syntax you want to use, then

\NewEnviron{myEnv}{%
  \expandafter\gdef\expandafter\myCommand\expandafter{\BODY}%
  \aftergroup\bgroup}

will work. But it's always difficult to understand what you really need.

1
  • Yup, the code from your last edit works! Thank you very much! Commented Jan 4, 2012 at 15:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .