[Tex/LaTex] How to highlight text with an arbitrary color

colorhighlightingsoul

Okay so I have the command

\newcommand{\hlc}[2][yellow]{{\sethlcolor{#1}\hl{#2}}}

in my preamble (after the inclusion of soul and xcolor packages), and colors that are already defined work perfectly well.

\hlc[pink]{hello}

gives me hello highlighted in pink. However, colour combinations don't output anything for me.

\hlc[cyan!50]{hello}

would output just

hello

without any colour.

I want a command that's completely generic (ie. let's me highlight with any colour combination I want). Is there any nice way to do that? I don't want to repeatedly use the command \setcolor either. I want to be able to input the colors right in the command.

Best Answer

The \sethlcolor macro does not understand the colour specifiction of x!y!z etc, it can work with named colors being defined with \definecolor only.

However, using xcolor there is a trick to support the colour definition:

\colorlet{foo}{x!y!z!} defines and transforms the specification into a colour named foo (this will overwrite an existing definition of the colour named foo, however.

Basically, it is similar to the macro \let\foo\foobar statement. Since all happens in a group (by definition of \hlc), the new colour foo is not known outside.

\documentclass{article}

\usepackage{xcolor}
\usepackage{soul}

\newcommand{\hlc}[2][yellow]{{%
    \colorlet{foo}{#1}%
    \sethlcolor{foo}\hl{#2}}%
}



\begin{document}

\hlc[pink]{hello}

\hlc[cyan!50]{hello}

\end{document}

enter image description here