1

I would like to measure the width of multi-line math code. My approach below does not always succeed. In the second example an additional line break is inserted: I believe that it has to do with the space produced around the \wedge symbol. I guess that an entirely different approach may be required? I appreciate any suggestions.

Cheers

\documentclass{article}

\makeatletter
\newlength{\mpbox@length}
\newcommand{\mpbox}[1]{%
\settowidth{\mpbox@length}{$\begin{array}{@{}l@{}}#1\end{array}$}%
\parbox[t]{\mpbox@length}{$#1$}%
}
\makeatother

\usepackage[osf,sc]{mathpazo}

\begin{document}

\noindent ExampleA
% expected result except for the overly wide box
\noindent\fbox{\parbox[t]{5cm}{$\wedge w$}}\\
% correctly computed width
\noindent \fbox{\mpbox{\wedge w}}\\

\noindent ExampleB
% expected result except for the overly wide box
\noindent\fbox{\parbox[t]{5cm}{$w\\\wedge w$}}\\
% incorrectly computed width resulting in an additional linebreak
\noindent \fbox{\mpbox{w\\\wedge w}}\\

\end{document}

enter image description here

3

Package varwidth to the rescue:

\documentclass{article}
\usepackage{varwidth}

\makeatletter
\newcommand{\mpbox}[1]{%
  \begin{varwidth}[t]{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}%
    $#1$%
  \end{varwidth}%
}
\makeatother

\usepackage[osf,sc]{mathpazo}

\begin{document}

\noindent ExampleA
% expected result except for the overly wide box
\noindent\fbox{\parbox[t]{5cm}{$\wedge w$}}\\
% correctly computed width
\noindent \fbox{\mpbox{\wedge w}}

\noindent ExampleB
% expected result except for the overly wide box
\noindent\fbox{\parbox[t]{5cm}{$w\\\wedge w$}}\\
% correctly computed width
\noindent \fbox{\mpbox{w\\\wedge w}}

\end{document}

Result

Remark:

Environment varwidth will decrease the width automatically to the actual used maximal line width. Since you want to put the result inside a \fbox I have decreased the maximal line width specification to leave room for the frame in case of overlong lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.