# Fit text to linewidth, shrinking only

I often have AVMs/tables that are just a bit too large and use \resizebox to fit everything in one line. Now, if the linewidth changes (switch from twocolumn to onecolumn) this results in enlarging the text.

\newcommand{\oneline}[1]{\resizebox{\linewidth}{!}{#1}}

Is there some way to reach the same result but without the possibility of enlarging the box?

The following example puts the contents in a box (this is done by \resizebox anyway), measures the width and applies \resizebox if necessary:

\documentclass{article}
\usepackage{graphicx}

\newcommand*{\restrictlinewidthbox}[1]{%
\begingroup
\sbox0{#1}%
\ifdim\wd0>\linewidth
\resizebox{\linewidth}{!}{\copy0}%
\else
\copy0 %
\fi
\endgroup
}

\setlength{\parindent}{0pt}

\begin{document}

\restrictlinewidthbox{\rule{10mm}{10mm}}

\restrictlinewidthbox{\rule{2\linewidth}{10mm}}

\end{document}

David Carlisle's trick

\resizebox{\ifdim\width>\linewidth\linewidth\else\width\fi}{!}{\rule{10mm}{10mm}}

also applies the resizing, if the natural \width is used. For example, the result in this case with pdflatex is a scaling factor of 1.00005 instead of 1.

## Rounding errors of \resizebox

The calculations of \resizebox are not too precise. Especially the box can be a little larger than specified. The following variant contributes the rounding error to the left and right of the box:

\newcommand{\restrictlinewidthbox}[1]{%
\begingroup
\sbox0{\ignorespaces#1\unskip}%
\leavevmode
\ifdim\wd0>\linewidth
\hbox to\linewidth{%
\hss\resizebox{\linewidth}{!}{\copy0 }\hss
}%
\else
\copy0 %
\fi
\endgroup
}
\resizebox{\ifdim\width>\linewidth\linewidth\else\width\fi}{!}{#1}}

probably works

\documentclass{article}

\newcommand*{\restrictlinewidthbox}[1]{%
}

\setlength{\parindent}{0pt}

\begin{document}

\restrictlinewidthbox{\rule{10mm}{10mm}}

\restrictlinewidthbox{\rule{2\linewidth}{10mm}}

\end{document}

(For the picture, I added the frame lines with geometry, not shown in the source.)

You can, of course, use \adjustbox directly or in its environment form: