Avoid interference between amsmath/fleqn and refstepcounter/label

amsmathcross-referencing

When I pdflatex the following twice:

\documentclass[fleqn]{article}

\usepackage{amsmath}

\begin{document}

\newcounter{mycounter}

\refstepcounter{mycounter}\label{foo}\ref{foo}

\refstepcounter{mycounter}\label{bar}\ref{bar}

\begin{equation} x\refstepcounter{mycounter}\label{baz}\ref{baz} \end{equation}

\ref{baz}

\refstepcounter{mycounter}\label{qux}\ref{qux}

\end{document}

then I get the following output:

1
2
  x1
1
4

If I remove \usepackage{amsmath} or [fleqn] or both then I get

1
2
  x3
3
4

The latter is what I want.

Can anyone tell me how to get the latter when using amsmath/fleqn ?

Best Answer

amsmath allows the end user to insert their own tags for numbered equations and therefore collects the body of math environments before processing them. This allows for proper parsing of the content, possibly delaying the execution of \label only after the equation counter has been stepped. It does, however, retain access to the original LaTeX \label via \ltx@label, which is appropriate for your use:

enter image description here

\documentclass[fleqn]{article}

\usepackage{amsmath}

\makeatletter
\newcommand{\ltxlabel}{\ltx@label}% User-level access to original LaTeX \label
\makeatother

\begin{document}

\newcounter{mycounter}

\refstepcounter{mycounter}\label{foo}\ref{foo}% 1

\refstepcounter{mycounter}\label{bar}\ref{bar}% 2

\begin{equation} x\refstepcounter{mycounter}\ltxlabel{baz}\ref{baz} \end{equation}

\ref{baz}% 3

\refstepcounter{mycounter}\label{qux}\ref{qux}% 4

\end{document}

\ltxlabel (or \ltx@label) will be executed immediately, using whatever counter was previously stepped (via \refstepcounter) as a label reference. In contrast, \label will only be used to reference the equation counter under amsmath.

Related Question