Incremento del contatore errato?

Sep 08 2020

Contesto

Vorrei aggiungere commenti evidenziati numerati automaticamente nel testo.

Tentativo

A seguito di questa risposta ho scritto quanto segue

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

\newcounter{mycounter}
\newcommand\showmycounter{\stepcounter{mycounter}\themycounter}

\definecolor{aquamarine}{rgb}{0.5, 1.0, 0.83}
\newcommand{\my}[1]{\sethlcolor{aquamarine} 
   \protect\hl{Comment \showmycounter: #1} \sethlcolor{yellow}}

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

\end{document}

che sfortunatamente per qualche strano motivo incrementa il contatore a passi di cinque.

Domanda

Potresti dirmi come ottenere un incremento di unità su questo contatore?

PS: Sono un po 'un principiante nella programmazione in lattice. Mi scuso in anticipo se questa domanda è stupida.

Risposte

3 Skillmon Sep 08 2020 at 20:26

Fornendo il mio commento come risposta: non dovresti inserire \stepcounterl'argomento di \hl. Invece incrementare il contatore prima e solo mettere \themycounterdentro \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}

4 egreg Sep 08 2020 at 20:53

L'elaborazione di \hlrichiede più passaggi sul suo argomento per eseguire misurazioni. Hai scoperto che ci sono cinque passaggi e ognuno incrementa il contatore. Nota che \stepcounteragisce a livello globale.

Puoi evitare di immergerti nelle viscere di soulcon ancora un po 'di lavoro.

\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}

Aggiungendo \global\steptruesi avvia la macchina che permette \stepcounteroncedi fare \stepcountersolo la prima volta.

Notare il gruppo aggiuntivo, che consente di evitare la ridichiarazione esplicita \sethlcolor.