\ProvidesPackage{tikzcdintertext}

\RequirePackage{tikz-cd}
\RequirePackage{etoolbox}
\usetikzlibrary{calc}

\@ifpackageloaded{geometry}{}{
    \edef\Gm@lmargin{\the\dimexpr1in + \hoffset + \oddsidemargin}
    \edef\Gm@rmargin{\the\dimexpr1in + \hoffset + \evensidemargin}
}

\newbox\mytikzcd@trialbox

\patchcmd\tikzcd@{#1]}{remember picture,#1]\let\intertext\mytikzcd@intertext}{}{\errorfailedtopatch}


\def\mytikzcd@addtosavedpaths#1{\xdef\tikzcd@savedpaths{\unexpanded\expandafter{\tikzcd@savedpaths}#1}}
\def\mytikzcd@intertext{
	\@ifnextchar[{\mytikzcd@intertext@}{\mytikzcd@intertext@[0pt]}
}

\def\mytikzcd@intertext@[#1]#2{
	\setbox\mytikzcd@trialbox=\vbox{\hsize\textwidth #2}
	\expandafter\\\expandafter[\the\dimexpr\ht\mytikzcd@trialbox+\dp\mytikzcd@trialbox+#1]
    \edef\mytikzcd@lmargin{\if@mparswitch\ifodd\thepage\space \Gm@lmargin\else \Gm@rmargin\fi\else \Gm@lmargin\fi}
	\mytikzcd@addtosavedpaths{
        \def\noexpand\mytikzcd@row{\the\numexpr\pgfmatrixcurrentrow-1}
        \noexpand\mytikzcd@findcolumn
        \noexpand\node[overlay, anchor=west,xshift=\mytikzcd@lmargin-2pt] at
        (current page.west |-
        {$(\noexpand\tikzcdmatrixname-\noexpand\mytikzcd@row-\noexpand\mytikzcd@column)!0.5!(\noexpand\tikzcdmatrixname-\the\pgfmatrixcurrentrow-1)$})
        \unexpanded{{\parbox{\textwidth}{#2}}};
	}
}


\def\mytikzcd@findcolumn{
    \def\mytikzcd@column{1}
    \expandafter\ifx\csname pgf@sh@pi@\tikzcdmatrixname-\mytikzcd@row-\mytikzcd@column\endcsname\pgfpictureid
        % Good, found it!
    \else
        \edef\mytikzcd@column{\numexpr\mytikzcd@column+1\relax}
        \ifnum\mytikzcd@tempcount<50
            \expandafter\expandafter\expandafter\mytikzcd@findcolumn
        \else
            \PackageError{tikzcdintertext}{%
                At least one of the cells in the row before an \noexpand\intertext needs to be nonempty. If you want more space,
                try using the optional argument to intertext. Alternatively, put a \noexpand\, or something invisible in one of the empty cells%
            }
        \fi
    \fi
}


\def\@gobbletonil#1\@nil{}
