Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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.

share|improve this answer
add comment

\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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.