# How can I set the color of an \sbox / \usebox?

In the following code, I want to produce a coloured shape, for example a \rule{1em}{1em}. If I use the \rule as is, it works as expected. However, putting it in an \sbox somehow breaks colouring and I get a black box.

\documentclass{standalone}
\usepackage{xcolor}

\newsavebox\myrule
\sbox\myrule{\rule{1em}{1em}}

\begin{document}

\color{red}
\usebox\myrule   % this gives me a black square
\rule{1em}{1em}  % this gives me a red square

\end{document}


Could someone kindly explain the reason for this behaviour? I know that the box could also be put in a macro definition instead, I'm just a bit confused why it doesn't work with \usebox. Moreover, is there some straightforward way to enable my \usebox\myrule to take on the current text colour, so that it can be basically be used like a usual glyph?

-

LaTeX color commands are designed to work like font commands. If you repeated your experiment with text saving default Roman text in the box and using the box in an italic context, the box contents would not go italic.

So as for font changes you need to put the colour command inside the saved box contents.

Depending on which colour back end you are using it is possible to subvert LaTeX's commands for example you could use a primitive \setbox instead of \sbox, but it's generally a bad idea to subvert things that LaTeX has gone to a lot of trouble to make work in a consistent way. If you use a system where colour is part of the font properties then colour necessarily works like font changes.

-

\sbox saves the visual content of a box for later use, i.e. you cannot change the color inside a saved box after its definition!

I think you probably need a macro instead of a saved box, like:

\newcommand{\myrule}{\rule{1em}{1em}}


And then:

\color{red}
\myrule


Or even better:

\newcommand{\myrule}[1][black]{\color{#1}\rule{1em}{1em}}


You can use \myrulelike that:

\myrule[red] % to draw a red box


or just:

\myrule % to draw a box with default color, here black

-