2

Welcome everybody. I have to use several colors in my text (more than 10). I want to build a command that takes 2 mandatories (the word and the color number) and prints the given word with the desired color. The following MWE gives more details:

\documentclass{article}
\usepackage{xparse}
\usepackage[dvipsnames]{xcolor}

\colorlet{col1}{red}
\colorlet{col2}{green}
\colorlet{col3}{blue}

\NewDocumentCommand{\cText}{mm}{\textcolor{#2}{#1}}

\begin{document}
  this is \cText{red}{col1}, this is \cText{green}{col2} and this is \cText{blue}{col3}.
  this is \cText{another red}{col1}, this is \cText{another green}{col2} and this is \cText{another red}{col1}.
  % The desired version is 
  %this is \cText{red}{1}, this is \cText{green}{2} and this is \cText{blue}{3}.
  %this is \cText{another red}{1}, this is \cText{another green}{2} and this is \cText{another red}{1}.{3}.
\end{document}

Any help, especially based on expl3, will be highly appreciated.

  • 2
    Welcome to TeX.SX. Why don't you use \textcolor{color}{text}? – nox Jul 21 '18 at 14:14
  • Nice suggestion. I updated my code. – R. ALOUI Jul 21 '18 at 14:20
  • 1
    I think if you change your command to \NewDocumentCommand{\cText}{mm}{\textcolor{col#2}{#1}} it'll do what you want. – Phelype Oleinik Jul 21 '18 at 14:22
  • 1
    Isn't this exactly the command you are trying to create? I don't see a reason for you to "recreate" it that way. You could write something like \let\cText\textcolor to use it rather than recreating a new macro that does exactly the same. – nox Jul 21 '18 at 14:23
  • 1
    but what you like to obtain can be done with \textcolor{<desired color>}{colored word(s)}. for this you not need any complication with new macro. you only need to define meaningful short names for your colors and that is. – Zarko Jul 21 '18 at 17:34
4

With a simpler interface for defining the colors. The “left-hand side” can be any string.

\documentclass{article}
\usepackage{xparse,xcolor}

\ExplSyntaxOn

\prop_new:N \g_aloui_colors_prop

\NewDocumentCommand{\setdocumentcolors}{m}
 {
  \prop_gset_from_keyval:Nn \g_aloui_colors_prop { #1 }
 }

\NewDocumentCommand{\cText}{mm}
 {
  \textcolor{ \prop_item:Nn \g_aloui_colors_prop { #2 } } { #1 }
 }

\ExplSyntaxOff

\setdocumentcolors{
  1=red,
  2=green,
  3=blue,
  x=pink,
}

\begin{document}

\cText{red}{1} \cText{green}{2} \cText{blue}{3} \cText{pink}{x}

\end{document}

enter image description here

  • You are awsome. This is exactly what I need. – R. ALOUI Jul 22 '18 at 8:25

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.