Wrong incrementation of counter?

The processing of \hl requires multiple passes over its argument in order to do measurements. You discovered that there are five passes and each one increments the counter. Note that \stepcounter acts globally.

You can avoid plunging into the innards of soul with some more work.

\documentclass{article}
\usepackage{color}
\usepackage{soul}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}

\newif\ifstep
\newcommand{\stepcounteronce}[1]{%
  \ifstep
    \global\stepfalse
    \stepcounter{#1}%
  \fi
}

\newcounter{mycounter}
\newcommand\showmycounter{\stepcounteronce{mycounter}\themycounter}
\newcommand{\my}[1]{{% an additional group to do \sethlcolor locally
  \global\steptrue
  \sethlcolor{aquamarine}%
  \hl{Comment \showmycounter: #1}%
}}

\begin{document}

some text 
\my{my first comment}

some more text
\my{my second comment}

This is again \hl{yellow}

\end{document}

By adding \global\steptrue you start the machinery that allows \stepcounteronce to do \stepcounter only the first time.

Note the additional group, which allows to avoid explicitly redeclaring \sethlcolor.

enter image description here


Providing my comment as an answer: You shouldn't put \stepcounter inside of the argument of \hl. Instead increment the counter before it and only put \themycounter inside \hl:

\documentclass{article}
\usepackage{color}
\usepackage{soul}

\newcounter{mycounter}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}
\DeclareRobustCommand{\my}[1]
  {%
    \sethlcolor{aquamarine}\stepcounter{mycounter}%
    \protect\hl{Comment \themycounter: #1} \sethlcolor{yellow}%
  }

\begin{document}
some text 
\my{my first comment}\\
some more text
\my{my second comment}

\end{document}

enter image description here

Tags:

Indexing