# How to glue center environment to the text?

I have very often a situation when I want that the center environment is glued to the preceding text, something like that:

Some text
%
\begin{center}
\begin{tikzpicture}
some commands
\end{tikzpicture}
\end{center}


Is it possible to make a general solution for that, for example defining new environment based on center or completely new environment to do the task?

• you could replace the % by \nopagebreak – David Carlisle Jul 23 '18 at 10:07
• I can confirm egreg's comment: \nopagebreak does not work. – Pygmalion Jul 23 '18 at 10:19
• hmph it could be made to work:-) @egreg can answer – David Carlisle Jul 23 '18 at 10:21

The \center environment uses \trivlist and issues an \item command, that adds \@beginparpenalty, which is usually −51. Thus a page break point is always available before center.

\documentclass{article}
\usepackage[lines=7]{geometry}
\usepackage{lipsum}

\makeatletter
\newenvironment{gluecenter}
{\@beginparpenalty\@M\center}
{\endcenter}
\makeatletter

\begin{document}

\lipsum*[2]
\begin{gluecenter}
This should stay
\end{gluecenter}

\end{document}


With center the centered line would be on a page by itself (the \lipsum paragraph has seven lines).

Another solution is to (ab)use displaymath, because a tikzpicture is independent on the mode it is called in.

Some text
$\begin{tikzpicture} ... \end{tikzpicture}$

• Thanks a lot. I decided for gluecenter, because I don't like to abuse things :) – Pygmalion Jul 23 '18 at 10:33
• @Pygmalion For a tikzpicture I'd go with $...$. – egreg Jul 23 '18 at 10:34
• Could you, in couple of words, say why? – Pygmalion Jul 23 '18 at 10:39
• @Pygmalion The display math mechanism is designed not to add a page break point before it and exploiting this method for adding a graphic object that must stay there is not a real abuse. – egreg Jul 23 '18 at 10:40
• It should be noted that gluecenter always leaves two text lines together with the picture, which is a plus compared to $/$ – Pygmalion Jul 23 '18 at 10:53