12

I was curious and found the following definition for the macro textcolor defined in the package xcolor:

\def\textcolor#1#{\@textcolor{#1}}
\def\@textcolor#1#2#3{\protect\leavevmode{\color#1{#2}#3}}

However, I use the macro with only two arguments and not three arguments:

\textcolor{blue}{foo}

What I don't understand for this definition is:

  1. What is the meaning of the syntax \textcolor#1#?
  2. What will be the third argument the macro \@textcolor will get in the example above?
14

This is primitive tex syntax that really shouldn't be used in a latex package. It's used here as in 1993 fitting this all into a 640K machine we were really short of space and saving a few dozen bytes by shortcutting the definition was worth it.

If you go

\def\foo#1#{zzz #1 zzz}

then #1 is everything from \foo to the first brace, so

\foo one two three {zzz}

then #1 would be one two three

Using this allows \textcolor to grab any optional arguments without actually parsing for them and then re-insert them so \color sees them.

so compare

\textcolor{blue}{foo}

and

\textcolor[rgb]{0,0,1}{foo}

in the first case #1 is empty so the expansion is

  \@textcolor{}{blue}{foo}

which is

  \protect\leavevmode{\color{blue}foo}

but in the second case #1 is [rgb] (including the brackets) so the first expansion is

\@textcolor{[rgb]}{0,0,1}{foo}

which is

 \protect\leavevmode{\color[rgb]{0,0,1}foo}

so the [rgb] isn't really ever seen by \textcolor as an optional argument, it is just grabbed and passed to \color.

  • Thank you for your clear answer. Is the second sharp after #1 really necessary then? – Saroupille Feb 14 at 17:42
  • 1
    @Saroupille Yes, otherwise it would only read the first token after \textcolor which would be [ in the case of an optional argument. – TeXnician Feb 14 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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