I tend to place my "float code" after the first call out (i.e., \ref) to the float. While I am drafting a document the first call out may change and I feel like I waste time finding the first call out and moving the float code to the correct place. Sometimes I also have float code that may or may not get used (e.g., a table that I am not sure I am going to include). What I would like to be able to do is define a figures environment and redefine \ref so that I can type something like:

This is a reference to figure~\ref{fig:D}.

This is a reference to figure~\ref{fig:A}.

This is a reference to figure~\ref{fig:C}.

This is a reference to figure~\ref{fig:C}.

  \begin{figure}\caption{This is figure A.}\label{fig:A}\end{figure}
  \begin{figure}\caption{This is figure B.}\label{fig:B}\end{figure}
  \begin{figure}\caption{This is figure C.}\label{fig:C}\end{figure}
  \begin{figure}\caption{This is figure D.}\label{fig:D}\end{figure}

and have LaTeX realize that what I want is:

This is a reference to figure~\ref{fig:D}\begin{figure}\caption{This is figure D.}\label{fig:D}\end{figure}.

This is a reference to figure~\ref{fig:A}\begin{figure}\caption{This is figure A.}\label{fig:A}\end{figure}.

This is a reference to figure~\ref{fig:C}\begin{figure}\caption{This is figure C.}\label{fig:C}\end{figure}.

This is a reference to figure~\ref{fig:C}.

The easiest way is to put each float in a separate file of the form

 \expandafter\ifx\csname r@fig:A\endcsname\relax\else\expandafter\endinput\fi
 \caption{This is figure A.}\label{fig:A}

then use


the figure will only be set once even if you input it multiple times as the \ifx test checks whether the label is defined and stops reading the file if it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.