20.5 \sbox & \savebox

Synopsis, one of:


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

This creates and uses a box register.

\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 box register over a \newcommand macro variable is efficiency, that LaTeX need not repeatedly retypeset the contents. See the example below.

The first two command invocations shown above, \sbox{box-cmd}{text} and \savebox{box-cmd}{text}, are roughly the same. 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{\newreg}{test \\ test} and \usebox{\newreg} then you get ‘testtest’, while if you enter \sbox{\newreg}{test \par test} and \usebox{\newreg} then you get ‘test test’, but no error or warning. To fix this use a \parbox or minipage as here.

      \item First item
      \item Second item

As an example of the efficiency of reusing a register’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
          \includegraphics[height=2in]{companylogo.png} \\
          Office of the President

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

If the register \noreg has not already been defined then you get something like ‘Undefined control sequence. <argument> \noreg’.

Unofficial LaTeX2e reference manual