[Tex/LaTex] Avoid recursion in \renewenvironment

environmentsmacros

I'm trying to redefine an environment in order to add a command after the \begin without having to add this command in manually everywhere.

For example, I'd like to replace every instance of \begin{figure} with \begin{figure}\foo where \foo is a function I've defined earlier:

\newcommand{foo}{This is foobar}

If I simply do:

\renewenvironment{figure}{\begin{figure}\foo}{\end{figure}}

then this creates a recursive definition of the figure environment.
This answer suggests using an intermediate command to get past the recursion problem when using \renewcommand.

But how can I get past the recursion problem when using \renewenvironment?

Best Answer

Patching existing environments or commands is almost a black art. One has to know in detail how the environment or command works.

Even saving a copy of \figure the newly defined environment will not work like the original one, particularly with respect to optional arguments.

The best place where placing code to be executed at every figure is in \@floatboxreset.

However, since you want to do it only for figure, there's something more to do.

\makeatletter
\g@addto@macro\@floatboxreset{\londonrob@floatcode{\@captype}}
\newcommand\londonrob@floatcode[1]{\@nameuse{londonrob@#1code}}
\newcommand\londonrob@figurecode{WHATEVER}
% similarly for \londonrob@tablecode if needed
\makeatother

Full example

\documentclass{article}

\usepackage{lipsum}

\makeatletter
\g@addto@macro\@floatboxreset{\londonrob@floatcode{\@captype}}
\newcommand\londonrob@floatcode[1]{\@nameuse{londonrob@#1code}}
\newcommand\londonrob@figurecode{WHATEVER}
% similarly for \londonrob@tablecode if needed
\makeatother

\begin{document}

\lipsum[2]

\begin{figure}[htp]

Something else

\caption{A caption}

\end{figure}

\lipsum[3]

\end{document}

Of course, in place of WHATEVER you'll add the code you want to be executed.

enter image description here

Related Question