# Can I automatically split an ocg environment over page breaks

I want to display ocgs in a pdf and use the ocgx package to achieve this. Sometimes the content I have in the environment is so long it needs a page break. This is incompatible with the ocg system and the content on the second page is always displayed instead of being optional. A simple fix would be to detect if the ocg is going to contain a page break and split the environment, e.g.

\begin{ocg}{Name}{label}{0}
\lipsum[1-10]
\end{ocg}


would be detected and the output would resemble the result of e.g.

\begin{ocg}{Name}{label1}{0}
\lipsum[1-3]
\end{ocg}

\clearpage

\begin{ocg}{Name}{label2}{0}
\lipsum[4-10]
\end{ocg}


How can I achieve this? I tried wrapping in a mdframed with beforebreak and afterbreak hooks to break and restart the ocg environment but I don't think ocgs like being nested in other environments...

-
I think the ocgs-p package is making things unneccessarily difficult here. From all I see, you should be able to use \ocg to start and \endocg to end an OCG, without nesting problems. –  Stephan Lehmke Dec 2 '13 at 16:00

I've been trying this myself but don't have the expertise to dig into mdframed.dtx and extract the obviously necessary box-splitting code. I've hacked together what seems to be a workable solution from Breakable vboxes.

I'd appreciate some help converting this plain-texy solution into a more latexy one.

\documentclass{article}
\usepackage{lipsum}
\usepackage{ocgx}

\newbox\totalocgbox
\newbox\partialocgbox
\newdimen\partialocgboxdim
\def\startocgbox{\par
\setbox\totalocgbox=\vbox\bgroup}
\def\endocgbox{\egroup\splitocgbox}

\def\splitocgbox{\ifvoid\totalocgbox\finishocgbox
\else\continuesplitting\fi}
\def\finishocgbox{\bigskip}

\def\continuesplitting{\null % In case this starts a new page
\dimen255=\dimexpr\pagegoal-\pagetotal-\pageshrink\relax
\ifdim\ht\totalocgbox<\dimen255
\setbox\partialocgbox=\box\totalocgbox
\colorthisbox
\else
\setbox\partialocgbox=\vsplit\totalocgbox to\dimen255
\colorthisbox\eject
\fi
\splitocgbox}

%TODO give this macro an appropriate name
\def\colorthisbox{%
\hbox{%
\begin{ocg}{Name}{Label}{1}%
\vbox{%
\unvbox\partialocgbox%
}
\end{ocg}%
}
}

\begin{document}

\startocgbox
\lipsum[1-20]
\endocgbox

\end{document}

-