How to perform a \global\renewenvironment
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}
Edit: First approach didn't seem to work with optional arguments.
Edit 2: Found an easier way using \globaldefs
:
Final answer:
In spirit of answering how to do a \renewenvironment
global:
\documentclass{article}
\begin{document}
\newenvironment{test}{HELLO}{WORLD}
\bgroup
\globaldefs=1
\renewenvironment{test}[1][world]{foo #1}{bar}
\egroup
\begin{test}[hello]
\end{test}
\end{document}
Second answer:
Two commands loosely inspired by \makeatletter
and \makeatother
: \makerenewglobal
and \makerenewlocal
. When \makerenewglobal
is called, \renewenvironment
do only global definitions. If \makerenewlocal
is called, it does the oposite: makes all \renewenvironment
-definitions local.
\documentclass{article}
\makeatletter
\let\@local@newenv\@newenv
\long\def\@global@newenv#1#2#3#4{%
\@ifundefined{#1}{\global\expandafter\let\csname#1\expandafter\endcsname\csname end#1\endcsname}{\relax}
{\let\def\gdef\expandafter\new@command\csname #1\endcsname#2{#3}}%
\l@ngrel@x\expandafter\gdef\csname end#1\endcsname{#4}%
}
\gdef\makerenewglobal{\global\let\@newenv\@global@newenv}
\gdef\makerenewlocal{\global\let\@newenv\@local@newenv}
\begin{document}
\newenvironment{test}{HELLO}{WORLD}
\bgroup\makerenewglobal
\renewenvironment{test}[1][world]{foo #1}{bar}
\egroup
\begin{test}[hello]
\end{test}
\end{document}
First answer:
In spirit of semi-generality; a command, \makeenvglobal{theenv}
, that makes a environment global:
\documentclass{article}
\gdef\makeenvglobal#1{%
\global\expandafter\expandafter\let\csname #1\expandafter\endcsname\csname #1\endcsname
\global\expandafter\expandafter\let\csname end#1\expandafter\endcsname\csname end#1\endcsname
}
\begin{document}
\newenvironment{test}{HELLO}{WORLD}
\bgroup
\renewenvironment{test}{foo}{bar}
\makeenvglobal{test}
\egroup
\begin{test}
\end{test}
\end{document}
prints foo bar