Two days I am looking for a solution but I have no more idea. This is my problem.
I'm trying to create a macro to automatically define new other macros to write references in a document. I want to create \createrefmacro
which take one parameter (for example Figure
). The \createrefmacro
will create a new macro called \refFigure
which will take one argument (the label of the reference) and an optional argument (I need an optional argument).
This is an MWE which should reproduce my problem (my original macro contains more details and the MWE may seem stupid!).
\documentclass{article}
\makeatletter
\def\createrefmacro#1{%
\edef\macro{\csname ref#1\endcsname}%
\edef\macro@i{\csname ref#1@i\endcsname}%
\expandafter\gdef\macro{%
\expandafter\@testopt\macro@i{}%
}%
\expandafter\gdef\macro@i[##1]##2{#1~\ref{##2}}%
}
\makeatother
\createrefmacro{Figure}
\createrefmacro{Table}
\begin{document}
\begin{table}[htp]
\caption{First table}\label{tab1}
\end{table}
\begin{figure}[htp]
\caption{First figure}\label{fig1}
\end{figure}
\begin{figure}[htp]
\caption{Second figure}\label{fig2}
\end{figure}
\refFigure{fig1}\par
\refTable{tab1}\par
\refFigure{fig2}\par
\end{document}
With \createrefmacro{Figure}
and \createrefmacro{Table}
, I create the \refFigure
and the \refTable
macros. I write a small document with only 2 figures and 1 table then I try to insert corresponding references in the document. However, the result is not what I expect as can be seen below
I tried few tricks with no success:
- Replace
\gdef
with\xdef
:- In
\macro
but the compilation produce an error - In
\macro@i
but the problem still happens
- In
- Use (plenty of)
\expandafter
to force the expansion of#1
in\macro@i
but I don't really know how and where to use it in this particular case.
I know the existence of packages like varioref
and the \labelformat
macro which should do the job in a better way. However, I need a solution which does not use external packages because of submissions as a scientific article (and I'm also very curious of the solution of this tricky problem!).