[Tex/LaTex] Access height of a \parbox

boxeslengthsparbox

Within a \parbox I can access its width via \linewidth (useful e.g. if I want to place an image as wide as the \parbox). Is there a way of accessing the height of a \parbox when the height is fixed by the optional argument? (Of course the question makes sense only in this case.)

\documentclass{article}

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

% here I'd like something like \parboxheight or similar
\fbox{\parbox[][100pt][t]{100pt}{Some text, some more text, and \the\linewidth, and the height?}}

\end{document}

enter image description here

Best Answer

The following solution patches \@iiiparbox to get the height in the second parameter. The value is stored in the dimension register \parboxheight.

If the height is not set, LaTeX uses \relax for this parameter. Then, \parboxheight is set to zero. If you want to know, whether the height parameter was set the optional argument, an additional switch can be used.

Example:

\documentclass{article}

\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \setlength{\parboxheight}{0pt}%
  \else
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother

\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\fbox{\parbox{100pt}{Some text, some more text, and \the\linewidth}}

\fbox{%
  \parbox[][80pt][t]{100pt}{%
    \raggedright
    Some text, some more text, and width \the\linewidth, %
    and the height \the\parboxheight.%
  }%
}
\end{document}

Result

With switch:

\documentclass{article}

\newif\ifparboxheight
\newdimen\parboxheight

\makeatletter
\newcommand*{\org@iiiparbox}{}
\let\org@iiiparbox\@iiiparbox
\renewcommand*{\@iiiparbox}[2]{%
  \ifx\relax#2%
    \parboxheightfalse
    \setlength{\parboxheight}{0pt}%
  \else
    \parboxheighttrue
    \setlength{\parboxheight}{#2}%
  \fi
  \org@iiiparbox{#1}{#2}%
}
\makeatother


\begin{document}

\setlength{\fboxsep}{-\fboxrule}

\newcommand*{\TestText}{%
  \raggedright
  Some text, some more text. The width is \the\linewidth
  \ifparboxheight
    \ and the height is \the\parboxheight
  \fi
  .%
}

\fbox{\parbox{100pt}{\TestText}}

\fbox{\parbox[][80pt][t]{100pt}{\TestText}}

\end{document}

Result with switch