[Tex/LaTex] How to perform a \global\renewenvironment

environmentsgroupingmacros

I need to execute a \renewenvironment within a group. Using \global\renewenvironment is not sufficient.

What changes do I need to make to the \DisableMyEnvironment macro in the MWE below so as to achieve the equivalent of \global\renewenvironment?

Currently, the MWE yields:

enter image description here

Once this is working as desired, the second line in blue should be in black.

Notes:

  • There are two test cases. The default one is within a \foreach and commenting out \def\ForeachTestCase{} uses a simple group.

References:

Code:

\def\ForeachTestCase{}%

\documentclass{article}
\usepackage{xcolor}
\usepackage{xstring}
\usepackage{tikz}

\newenvironment{MyEnvironment}[1][blue]{%
    \begingroup
        \color{#1}%
}{%
    \endgroup
}%

\newcommand*{\DisableMyEnvironment}{%
    %% How make this global??
    \renewenvironment{MyEnvironment}[1][]{}{}%
}%

\newcommand*{\MyTestText}[1]{%
    Some before text

    \begin{MyEnvironment}
        This should be in #1.
    \end{MyEnvironment}

    Some after text%
}

\begin{document}

\MyTestText{blue}

%\DisableMyEnvironment% <-- This works, but want it to work when used in a group as follows
\ifdefined\ForeachTestCase
    \foreach \x in {1,...,3} {%
        \IfStrEqCase{\x}{%
            {1}{}%
            {2}{\DisableMyEnvironment}%
            {3}{}%
        }%
    }
\else
    \begingroup
        \DisableMyEnvironment
    \endgroup
\fi

\medskip\par
\MyTestText{black}

\end{document}

Best Answer

Create a dummy (or alternate) environment in the global scope (preamble), here, XEnvironment, and then in the \DisableMyEnvironment macro, globally reassign by way of

\global\let\MyEnvironment\XEnvironment%
\global\let\endMyEnvironment\endXEnvironment%

MWE:

\documentclass{article}
\usepackage{xcolor}
\newenvironment{XEnvironment}[1][]{}{}%
\newenvironment{MyEnvironment}[1][blue]{%
    \begingroup
        \color{#1}%
}{%
    \endgroup
}%

\newcommand*{\DisableMyEnvironment}{%
    %% How make this global??
    \global\let\MyEnvironment\XEnvironment%
    \global\let\endMyEnvironment\endXEnvironment%
}%

\newcommand*{\MyTestText}[1]{%
    Some before text

    \begin{MyEnvironment}
        This should be in #1.
    \end{MyEnvironment}

    Some after text%
}

\begin{document}

\MyTestText{blue}

%\DisableMyEnvironment% <-- This works, but want it to work when used in a group as follows
\begingroup
    \DisableMyEnvironment
\endgroup

\medskip\par
\MyTestText{black}


\end{document}

enter image description here