Next: , Previous: , Up: Boxes   [Contents][Index]

20.5 \sbox & \savebox

Synopsis, one of:

\sbox{box-cmd}{text}
\savebox{box-cmd}{text}
\savebox{box-cmd}[width]{text}
\savebox{box-cmd}[width][pos]{text}


Typeset text just as with \makebox (see \mbox & \makebox) except that LaTeX does not output it but instead saves it in a storage bin named box-cmd. The bin name box-cmd begins with a backslash, \. You must have previously allocated the bin box-cmd with \newsavebox (see \newsavebox).The \sbox command is robust while \savebox is fragile (see \protect).

This creates and uses a bin.

\newsavebox{\fullname}
\sbox{\fullname}{John Jacob Jingleheimer Schmidt}
...
\usebox{\fullname}! His name is my name, too!
Whenever we go out, the people always shout!
There goes \\usebox{\fullname}!  Ya da da da da da da.


One advantage of using and reusing a bin over a \newcommand is efficiency, that LaTeX need not repeatedly retypeset the contents. See the example below.

The first two command invocations, \sbox{box-cmd}{text} and \savebox{box-cmd}{text}, are roughly equivalent. As to the third and fourth, the optional arguments allow you to specify the box width as width, and the position of the text inside that box as position. See \mbox & \makebox for the full description.

In the \sbox and \savebox commands the text is typeset in LR mode so it does not have line breaks (see Modes). If you use these then LaTeX doesn’t give you an error but it ignores what you want: if you enter \sbox{\newbin}{test \\ test} and \usebox{\newbin} then you get ‘testtest’, while if you enter \sbox{\newbin}{test \par test} and \usebox{\newbin} then you get ‘test test’, but no error or warning. To fix this use a \parbox or minipage as here.

\savebox{\abin}{%
\begin{minipage}{\linewidth}
\begin{enumerate}
\item First item
\item Second item
\end{enumerate}
\end{minipage}}
...
\usebox{\abin}


As an example of the efficiency of reusing a bin’s contents, this puts the same picture on each page of the document by putting it in the header. LaTeX only typesets it once.

\usepackage{graphicx}  % all this in the preamble
\newsavebox{\sealbin}
\savebox{\sealbin}{%
\setlength{\unitlength}{1in}%
\begin{picture}(0,0)%
\put(1.5,-2.5){%
\begin{tabular}{c}
\includegraphics[height=2in]{companylogo.png} \\
Office of the President
\end{tabular}}
\end{picture}%
}
\markright{\usebox{\sealbin}}

The picture environment is good for fine-tuning the placement.