# Detect misplaced label in figure

I realized that I sometimes write :

\begin{figure}
...
\label{fig:foo}
\caption{Bla}
\end{figure}


\begin{figure}
...
\caption{Bla}
\label{fig:foo}
\end{figure}


Which results in wrong reference numbers.

Is there an easy way to catch all these errors?

• Not really; LaTeX is just doing what you tell it to do (labeling the last element that had an associated number generated). There's no way for it to know that you mean something other than what you code. – Paul Gessler Mar 10 '14 at 17:40

If your editor supports regular expressions this expression should find all wrong label+caption statements

\\label\{.*\}\r*\n*\\caption\{.*\}

• Thanks for your suggestion. I used pcregrep instead. – Maxime Mar 11 '14 at 13:07

I would suggest to insert systematically the \label command inside the argument of \caption to avoid that sort of “errors”:

\caption{\label{fig:foo}Bla}


Based on Oliver's answer, I used:

pcregrep -M "\\\label{.*}\r*\n*\\\caption{.*}" */*.tex