6

--- update ---

Any comments, is this a bug in the caption package or do have have to protect \refstepcounter somehow?

--- \update ---

I have the following MWE:

\documentclass{book}

\usepackage{xparse}
%\usepackage{caption}

\newcounter{mycounter} % make a counter
\setcounter{mycounter}{0} % init the counter

\NewDocumentCommand \mymark {} {%
\refstepcounter{mycounter}%
\textsuperscript{\themycounter}}

\begin{document}
%
one\mymark

\begin{figure}
\caption{two\mymark}
\label{lab:1}
\end{figure}%

three\mymark

\end{document}

without caption package it produces

no_caption

but if I add the package

with_caption

Why is the numbering incorrect?

1 Answer 1

4

The caption package typesets the caption twice.

You can add some test to see whether you're in a caption and, in that case, do the stepping only the first time. I use \caption@beginhook to inject the necessary code when typesetting the caption.

\documentclass{book}

\usepackage{xparse}
\usepackage{caption}

\newcounter{mycounter} % make a counter

\NewDocumentCommand\mymark{}{%
  \ifandyincaption
    \ifandysteppedcounter
    \else
      \refstepcounter{mycounter}%
      \global\andysteppedcountertrue
    \fi
  \else
    \refstepcounter{mycounter}%
  \fi
  \textsuperscript{\themycounter}%
}
\newif\ifandyincaption
\newif\ifandysteppedcounter

\makeatletter
\AtBeginDocument{%
  \g@addto@macro\caption@beginhook{%
    \andyincaptiontrue
    \global\andysteppedcounterfalse
  }%
}
\makeatother


\begin{document}

one\mymark

\begin{figure}
\caption{two\mymark}
\label{lab:1}
\end{figure}

three\mymark (\ref{lab:1})

\end{document}

enter image description here

2
  • 1
    Is there a particular reason, why the caption package typesets twice?
    – Andy
    Feb 17, 2014 at 16:03
  • 1
    @Andy It wants to check whether the caption fits on one line and uses a slightly different method than standard LaTeX.
    – egreg
    Feb 17, 2014 at 16:06

You must log in to answer this question.

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