19

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.

1 Answers1

24

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

  • I'm getting the error: ! Use of @undeclaredcolor doesn't match its definition. @ifnextchar ... \reserved@d =#1\def \reserved@a { #2}\def \reserved@b {#3}\f... l.8 \hlc[pink]{hi} If you say, e.g., \def\a1{...}', then you must always put1' after `\a', since control sequence names are made up of letters only. The macro here has not been followed by the required stuff, so I'm ignoring it. – Osama Kawish Feb 09 '17 at 16:55
  • Sorry. Not getting it after copying and pasting your code. Must be typo somewhere... – Osama Kawish Feb 09 '17 at 16:56
  • @OsamaKawish: Works for me, even after copying again from here... –  Feb 09 '17 at 16:58
  • Yes same here. I meant there must be a bracket mistake or something in mine after I tried changing by hand on my old code. – Osama Kawish Feb 09 '17 at 16:59
  • @OsamaKawish: Which is hard to detect for me since I don't see your code... –  Feb 09 '17 at 17:00
  • It's fine. I can figure these out on my own. :) – Osama Kawish Feb 09 '17 at 17:01
  • This is brilliant. Works great for me using custom colors predefined such as \definecolor{coral}{HTML}{F45B69} – MilleCodex Jan 15 '24 at 00:56