# [texhax] Changing font color of a saved box of text - is it possible?

Tue Sep 4 12:56:09 CEST 2012

On Tue, Sep 04, 2012 at 11:20:05AM +0100, Ivan Griffin wrote:

> I'd like to be able to save a box, and then change the color of the
> font in it when I come to use it.  Is this possible?
>
> I suspect not (as the typesetting/macro expansion is already
> complete within the box),

LaTeX puts the current color inside the box, thus that the color
does not change if used in different color contexts. It is a feature
that the color of a box does not change.

> and saving multiple boxes and chosing the
> one with the color I want isn't practical in my particular
> application. I guess I'm asking if there is any sneaky tricks I can
> use to override the color in the saved box?
>
> Here is a small working example that shows what I'm trying to do:
> Ideally, both lines of text should be the same color (red).
>
> --------------------------------------------
>
> \documentclass{article}
>
> \usepackage{xcolor}
>
> \newsavebox{\boxFoo}
>
> \begin{document}
>
> \begin{lrbox}{\boxFoo}
> This is test 1. \end{lrbox}
>
> \color{red}
>
> \usebox{\boxFoo}
>
> This is test 2.
> \end{document}
>
> --------------------------------------------
>
> What I see is that "This is test 1" is typeset in black, whereas
> "This is test 2" is typeset in red.

Why can't you use a simple macro?

\newcommand*{\macroFoo}{This is test1.}
\color{red}
...
\macroFoo
...

If you need boxes, this can be done using the low level TeX interface:

\setbox\boxFoo=\hbox{%
\begingroup
This is test 1.%
\endgroup
}

The group with \begingroup and \endgroup is a protection for the case that
color commands are used inside the text. Color resetting is done outside
the current group and would slip out of the box without the additional
group.

Yours sincerely
Heiko Oberdiek