18

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.

2
  • 1
    Apparently sethlcolor does not understand this colour specification and uses named colours only
    – user31729
    Feb 9, 2017 at 16:39
  • Probably you should define the color with a name first and then use it.
    – TeXnician
    Feb 9, 2017 at 16:40

1 Answer 1

22

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

6
  • 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 put 1' 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. Feb 9, 2017 at 16:55
  • Sorry. Not getting it after copying and pasting your code. Must be typo somewhere... Feb 9, 2017 at 16:56
  • @OsamaKawish: Works for me, even after copying again from here...
    – user31729
    Feb 9, 2017 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. Feb 9, 2017 at 16:59
  • @OsamaKawish: Which is hard to detect for me since I don't see your code...
    – user31729
    Feb 9, 2017 at 17:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .