# Grouping Negates Effect of \centering

Why does the use of \begingroup, \endgroup negate the effect of centering in the MWE?

The MWE below yields a left aligned figure (not desired), with subsequent text on the left (desired):

But if I remove the \begingroup, \endgroup, then things work as desired as far as the \centering goes, but then the subsequent text is also centered?

## Question:

• I thought the entire purpose of grouping was to localize the effect. So, what is the subtlety of grouping that results in this behavior?
• How do I keep the grouping, yet also have the centering? I would like to ensure that any settings that are changed via the inserted figure are kept local to that figure.

## Code:

\documentclass{article}
\usepackage{showframe}
\usepackage{pgfplots}

%\usepackage{filecontents}% Commented to prevent overwriting myFig.tex
\begin{filecontents*}{myFig.tex}
\def\YLabel{$f(x) = x^2 - x +4$}
\begin{tikzpicture}
\begin{axis}[ xlabel=$x$, ylabel=\YLabel]
\end{axis}
\end{tikzpicture}
\end{filecontents*}

\newcommand*{\InsertFigure}[1]{%
\IfFileExists{#1}{%
\begingroup%
\centering%
\input{#1}%
\endgroup%
}{}%
}%

\begin{document}
\InsertFigure{myFig.tex}

\textbf{Text on left.}
\end{document}

-

You need to end the paragraph before closing the group (\centering and other similar commands as well as font size switches (\small, \large, \Huge, etc.), need to "see" an end of paragraph to work correctly):

\documentclass{article}
\usepackage{showframe}
\usepackage{pgfplots}

%\usepackage{filecontents}% Commented to prevent overwriting myFig.tex
\begin{filecontents*}{myFig.tex}
\def\YLabel{$f(x) = x^2 - x +4$}
\begin{tikzpicture}
\begin{axis}[ xlabel=$x$, ylabel=\YLabel]
\end{axis}
\end{tikzpicture}
\end{filecontents*}

\newcommand*{\InsertFigure}[1]{%
\IfFileExists{#1}{%
\begingroup%
\centering%
\input{#1}\par%
\endgroup%
}{}%
}%

\begin{document}
\InsertFigure{myFig.tex}

\textbf{Text on left.}
\end{document}


-
Well that was easy!! Can't believe I forgot to try that!! –  Peter Grill Jan 13 '13 at 4:02
I guess what you mean by "font switches" is rather a use of something just as \small or \Large and the effect on \baselineskip? because I don't see offhand (except in math mode) other "font switches" that need to see the end of the paragraph (resp. math mode) to work correctly. –  jfbu Jan 13 '13 at 9:19
@jfbu yes Gonzalo means the font size commands here which as you say will change the font but mess up the baseline spacing if used this way. –  David Carlisle Jan 13 '13 at 9:31
@DavidCarlisle ah ok. And I probably should add, regarding math mode, that I was not thinking of any LaTeX user level command but of the fact that TeX uses in the entire formula the font families as defined at the end of the math mode. –  jfbu Jan 13 '13 at 9:36
@jfbu yes, as David mentioned, I meant those size switches. I edited my answer to make that clear. –  Gonzalo Medina Jan 13 '13 at 14:36