0

I'd like to construct a macro like \parbox, but with a style of spread align, as the option [s] in \makebox. That is to say, when the width of text is less than the defined width(only one line of text), the text will typeset spread align. If the width of text is longer than defined width, it behaves just as \parbox.

Example:

\documentclass{article}
%\usepackage{...}

\begin{document}
\newcommand\newparbox[3][]{...}
|\newparbox{8em}{AB AB}|\par
|\newparbox[t]{8em}{AB AB AB AB AB AB AB}|
\end{document}

enter image description here

Bernard
  • 271,350
lyl
  • 2,727

1 Answers1

2

You may check if the width of the argument is bigger than the given width with \ifdim:

\documentclass{article}

\begin{document}

\makeatletter
\newcommand\newparbox[3][]{%
    \settowidth\@tempdima{#3}
    \ifdim\@tempdima>#2\relax
        \parbox[#1]{#2}{#3}%
    \else
        \makebox[#2][s]{#3}%
    \fi
}
\makeatother

|\newparbox{8em}{AB AB}|\par
|\newparbox[t]{8em}{AB AB AB AB AB AB AB}|
\end{document}

Edit: LaTeX version:

\documentclass{article}

\usepackage{ifthen}

\begin{document}

\makeatletter
\newcommand\newparbox[3][]{%
    \settowidth\@tempdima{#3}%
    \ifthenelse{\lengthtest{\@tempdima > #2}}{\parbox[#1]{#2}{#3}}{\makebox[#2][s]{#3}}%
}
\makeatother

|\newparbox{8em}{AB AB}|\par
|\newparbox[t]{8em}{AB AB AB AB AB AB AB}|
\end{document}
zetaeffe
  • 633
  • Thank you for your quick answer. I tried with this \ifthenelse{\lengthtest{\widthof{#3} < #2}} (\usepackage{ifthen,calc}, but it fails to compile. Wht's wrong with this? And could you provide with a Latex version of your code? – lyl Feb 16 '19 at 14:28
  • @lyl You can't use \widthof in the argument of \lengthtest. – egreg Feb 16 '19 at 14:48
  • The reason why \widthof is used is, I don't want introduce a new length variable. Can I get this? And why \widthof can not be used in \lengthtest? – lyl Feb 16 '19 at 14:54
  • @lyl You can't, that's all: TeX can't perform assignments in the middle of the evaluation of a conditional. – egreg Feb 16 '19 at 15:16
  • If there are \\ in #3, how to handle it to get exactly the same effect above. I mean, not just the first line, every line(delimited by \\), if the length of a certain line is shorter than #2, then spread align it, otherwise, typeset like \parbox – lyl Feb 17 '19 at 01:48