3

In Cool Text Highlighting in LaTeX, Gumbo offered, in a comment to Caramdir's answer, \hlc, a modification of soul's \hl to allow choosing the highlighting color on the fly.

\hlc, though, leaves excess space around the highlighted text, particularly before but also after.

Here is a MWE:

\documentclass[11pt]{book}
\usepackage{xcolor} 
\usepackage{soul}
\newcommand{\hlc}[2][yellow]{ {\sethlcolor{#1} \hl{#2}} }
\begin{document}
In the source there is\hlc[yellow]{no space}between highlighted-surrounding text.
\end{document}

and here is the output:

Excess Space

schremmer
  • 2,107

1 Answers1

2

Several points:

  1. You had excess spaces within your macro definition, notably upon entry, upon exit and also just prior to \hl. There are times when spaces in a macro definition have no effect, for example in math mode, or trailing the name of a macro are two notable examples. However, in general, spaces in a macro definition are translated as spaces in the output. This is where your spurious spaces arose, and

  2. I added \unskip and \ignorespaces to the definition, to remove spaces that surround the \hlc invocation, as well. You may not want those in your actual definition, but it is to show how the macro can reach outside of itself to also remove external surrounding spaces.

The MWE:

\documentclass[11pt]{book}
\usepackage{xcolor} 
\usepackage{soul}
\newcommand{\hlc}[2][yellow]{\unskip{\sethlcolor{#1}\hl{#2}}\ignorespaces}
\begin{document}
In the source there is \hlc[yellow]{no space} between highlighted-surrounding text.
\end{document}

enter image description here

  • A perfect answer: answers the question and explains why. Thanks – schremmer Jun 08 '17 at 18:52
  • 1
    @schremmer (I will parenthetically add that this is the reason you will see % signs at the end of each line of a multi-line macro definition... the % eats the spurious space that would otherwise be introduced) – Steven B. Segletes Jun 08 '17 at 18:54
  • Ah! I have "always" dutifully ended each line in my preamble with a % (removed it for the question here!) but had no idea why! Now I know. :-)) Thanks again. – schremmer Jun 09 '17 at 02:04
  • 1
    @schremmer In general, not all preamble lines need the %, only those that are inside of macro definitions, or those in the middle of a multi-line argument where spaces are not intended. But I'm happy to see the "light bulb go on." Learn more at https://tex.stackexchange.com/questions/7453/what-is-the-use-of-percent-signs-at-the-end-of-lines – Steven B. Segletes Jun 09 '17 at 02:39