Control page breaks in multiple frames via mdframed

I am having an issue with mdframed, where I've created a frames inside frames spanning several pages, but I'd like mdframed to split them differently across the pages, so as much of the text on page two is moved to page one.

Here is the output of the code:

The desired result should look like this, which I've created in Microsoft Paint:

Here is the code:

\documentclass{article}
\usepackage{mdframed,lipsum}
\newmdenv[
leftmargin = 0pt,
innerleftmargin = 1em,
innertopmargin = 0pt,
innerbottommargin = 0pt,
innerrightmargin = 0pt,
rightmargin = 0pt,
linewidth = 1pt,
topline = false,
rightline = false,
bottomline = false
]{leftbar}
\begin{document}
\lipsum[1]
\begin{leftbar}
\lipsum[2]
\begin{leftbar}
\lipsum[3-5]
\end{leftbar}
\end{leftbar}
\end{document}


Update: There is another issue, where the frame exceeds the page margins:

One can see the page number on top of the frame in the image. I'd like for the frame to break across pages and stay inside the page margins. The result was obtained by changing \lipsum[3-5] to \lipsum[3-20] in the previous MWE.

You can use another macros than mdframed for your purpose. For example the following macros:

\documentclass{article}
\usepackage{lipsum}

\newcount\tmpnum
\def\endleftline{\par \setbox1=\vbox{}\endleftlineA}
\def\endleftlineA{
\setbox0=\lastbox
\ifvoid0 \expandafter \endleftlineB \else
\global\dimen1=\ht0
\tmpnum=\lastpenalty \unpenalty
\global\setbox1=\vbox{\ifnum\tmpnum=0 \else \penalty\tmpnum \fi
\vskip\dimen0 \hbox{\hbox to\leftskip{\hss\leftrule\kern.4em}\kern-\leftskip\box0}
\unvbox1}
\expandafter \endleftlineA \fi
}
\vskip-\dimen1 \unvbox1
}
\def\leftrule{\vbox{\kern-.7\baselineskip
\hbox{\vrule width1pt height.7\baselineskip depth\ifdim\ht1>0pt.4\else.1\fi\baselineskip}
\kern-\prevdepth}
}

\begin{document}
\lipsum[1]
\leftline
\lipsum[2]
\leftline
\lipsum[3-6]
\endleftline
\endleftline
\lipsum[1]

\end{document}

• The solution works perfectly for text, but if I add an eqnarray*, the commands stop working.
– Nick
Apr 3, 2018 at 10:45
• It also sadly does not work with footnotes or itemize for example Dec 4, 2021 at 11:12

After closer inspection of the manual I found the following text:

A nested mdframed environment can’t be splitted.

That explains it.