How to use \pdfcolorstack?

Consider this code:

``````\chardef\Color=\pdfcolorstackinit page direct{0 g}
\pdfcolorstack \Color push {1 0 0 rg 1 0 0 RG}
red
\pdfcolorstack \Color pop {}
black
\hrule height 1pt width 50pt

\bye
``````

I try to use the color stack to write "red" in red and switch back to the previous color (black) and write the word "black" in that color (works fine). But why is the `\hrule` still affected by the color switch?

Obviously I don't know how to use `\pdfcolorstack`, but what is the intended semantic? I'd like to keep `1 0 0 RG` as I also want to set the color for stroking operations.

• a bit strange. As you hint, it works fine if you just push `{1 0 0 rg }` including colouring any rules that are in that scope. so presumably rules are filled rather than stroked, I haven't checked. Does pdftex introduce stroke rendering itself or do you mean to interact with other code from pdfliteral? latex uses rg and RG I'll see what it does ... – David Carlisle Sep 13 '13 at 13:10

You have already found the missing `0 G` in the initialization. But the latter is not needed for the main color stack. From `NEWS` of pdfTeX:

• \pdfcolorstackinit
A stack is initialized by \pdfcolorstackinit. It expands to the number of the new stack. The common case, the traditinal color stack is already initialized as first stack: \pdfcolorstackinit page direct {0 g 0 G} The keyword "page" means that this stack is page based. At the start of the new page, the current stack value is automatically set.

All you need is:

``````\chardef\Color=0 %
``````

BTW, the LaTeX `color` package with driver `pdftex.def` can also be used with plain TeX via the help of `miniltx.tex`:

``````\input miniltx
\makeatletter
\input color.sty
\resetatcatcode

\textcolor{red}{red} \ black
\hrule height 1pt width 50pt

\bye
``````

• Great! I was able to significantly reduce my TeX code from 17 lines to 6 lines (4 TeX commands) :) – topskip Sep 13 '13 at 17:09

Embarrassing:

It seems as if two characters fix the issue (`0 G` in `\pdfcolorstackinit`):

``````\chardef\Color=\pdfcolorstackinit page direct{0 g 0 G}
\pdfcolorstack \Color push {1 0 0 rg 1 0 0 RG}
red
\pdfcolorstack \Color pop {}
black
\hrule height 1pt width 50pt

\bye
``````

It seems to be what PDFTeX uses to reset the color. I wonder where this is documented...