# How to have automatic ordering of floats?

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:

\documentclass{article}
\begin{document}
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{figures}
\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}
\end{figures}
\end{document}


and have LaTeX realize that what I want is:

\documentclass{article}
\begin{document}
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}.
\end{document}

-

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
\begin{figure}
.....
\caption{This is figure A.}\label{fig:A}
\end{figure}


then use

\input{figAfile}\ref{fig:A}


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.

-