Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I would like to make a conditional reference to an optional label in my latex document, see the Minimum Working Example below. Hence, IF the label exists somewhere in the document, THEN a reference will be made, some other place in the document, to that label. I am using the "etool" package, but I am not sure if any of the commands there are usefull for my purpose.

\documentclass{article}

\begin{document}

\section{Method}
...the method is based on Anderson et. al 2012,
% CONDITIONAL FUNCTION 
% IF \label{sec-appendix} EXISTS THEN:
{a summary of which is given in Appendix \ref{sec-appendix}.}
% ELSE
{not explained here.}
% END OF CONDITIONAL FUNCTION

\appendix
\section{Appendix}
\label{sec-appendix}

\end{document}
share|improve this question

1 Answer 1

up vote 8 down vote accepted

We can exploit the fact that \label{xyz} defines \r@xyz:

\documentclass{article}

\makeatletter
\newcommand{\iflabelexists}[3]{\@ifundefined{r@#1}{#3}{#2}}
\makeatother

\begin{document}

\section{Method}
...the method is based on Anderson et. al 2012,
\iflabelexists{sec-appendix}
  {a summary of which is given in Appendix~\ref{sec-appendix}.}
  {not explained here.}

\appendix
\section{Appendix}
\label{sec-appendix}

\end{document}

Of course this stabilizes after a couple of runs. If you add \end{document} before \appendix you'll see.

With etoolbox it's simpler, but essentially equivalent:

\usepackage{etoolbox}
\newcommand{\iflabelexists}[3]{\ifcsundef{r@#1}{#3}{#2}}
share|improve this answer
    
Thanks a lot! Your solution looks very promissing, I will test it immediately : ) –  Espen Donali Apr 29 '13 at 10:48
    
Hi again..I have encountered one potential problem with the code you suggested. If there is any \ref{sec-appendix} above the \iflabelexists line, then your code interpret this as if the label exists, that is, that \label{sec-appendix} exists, when I add \end{document} before \appendix. –  Espen Donali Apr 29 '13 at 15:25
    
@EspenDonali Fixed. –  egreg Apr 29 '13 at 15:30
    
Thanks for your help, it works fine ! –  Espen Donali Apr 29 '13 at 15:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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