# Change page margin inside own environment

I would like to define an environment, that inserts a page with different margins than defined in the preamble.

I tried using the following LaTeX code.

\documentclass[a4paper,10pt]{article}

\usepackage{blindtext}

\newenvironment{myenv}{
\blindtext[2]
}{
\newpage

\restoregeometry
}

\begin{document}

\begin{myenv}

\end{myenv}
\blindtext[10]
\end{document}


Unfortunately on the second page there is an unexpected page break after a few lines. The following code produces the desired result.

\documentclass[a4paper,10pt]{article}

\usepackage{blindtext}

\newenvironment{myenv}{
\blindtext[2]
}{
\newpage
}

\begin{document}

\begin{myenv}

\end{myenv}
\restoregeometry
\blindtext[10]
\end{document}


However I do not want to write \restoregeometry manually each time I use myenv. Can anyone explain me the difference between the two code pieces above and provide a solution for this problem? Thanks.

• Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – karlkoeller Oct 2 '13 at 15:27

I don't know what you are trying to do, but the command \AfterEndEnvironment from the etoolbox package can help you in this.

It inserts some code just after the environment is ended.

\usepackage{etoolbox}
\AfterEndEnvironment{myenv}{\restoregeometry}


should permit you to achieve what you want.

Complete MWE

\documentclass[a4paper,10pt]{article}

\usepackage{blindtext}

\usepackage{etoolbox}
\AfterEndEnvironment{myenv}{\restoregeometry}

\newenvironment{myenv}{%
\blindtext[2]%
}{%
\newpage%
}

\begin{document}

\begin{myenv}

\end{myenv}
\blindtext[10]
\end{document}


To answer the question in your comment, I think that \restoregeometry doesn't work if you put it at the environment end, because the latter forms a group.

In fact, if you tell LaTeX to execute \restoregeometry after the group is finished with the command \aftergroup, you have a solution that hasn't the need for \AfterEndEnvironment:

\newenvironment{myenv}{%