Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if a label is already defined in LaTeX?

Tags:

label

latex

I edited the question after David Hanak's answer (thanks btw!). He helped with the syntax, but it appears that I wasn't using the right function to begin with.

Basically what I want is to let the compiler ignore multiple definitions of a certain label and just use the first. In order to do that, I thought I'd just do something like this:

    \makeatletter
    \newcommand{\mylabel}[1]{
        \@ifundefined{#1}{\label{#1}}{X}
    }
    \makeatother

This does not work though, because the first option is always chosen (it doesn't matter if the label is defined or not). I think the \@ifundefined (and the suggested \ifundefined) only work for commands and not for labels, but I don't really know much about LaTeX. Any help with this would be great! Thanks!

Much later update: I marked David Hanak's response as the correct answer to my question, but it isn't a complete solution, although it really helped me. The problem is, I think but I'm no specialist, that even though David's code checks to see if a label is defined, it only works when the label was defined in a previous run (i.e. is in the .aux file). If two \mylabels with the same name are defined in the same run, the second will still be defined. Also, even if you manage to work around this, it will make LaTeX use the first label that you defined chronologically, and not necessarily the first in the text. Anyway, below is my quick and dirty solution. It uses the fact that counters do seem to be defined right away.

\newcommand{\mylabel}[1]{%
    \@ifundefined{c@#1}{%
        \newcounter{#1}%
        \setcounter{#1}{0}%
    }{}%
    \ifthenelse{\value{#1} > 0}{}{%
        \label{#1}%
        \addtocounter{#1}{1}%
    }%
}

I'm not sure if it is necessary to initialize the counter to 0, as it seems like a likely default, but I couldn't find if that was the case, so I'm just being safe. Also, this uses the 'ifthen' package, which I'm not sure is necessary.

like image 766
Jordi Avatar asked Dec 22 '22 13:12

Jordi


1 Answers

I am also not a LaTeX expert, however after one day of trying and searching the internet the following worked for me. I have used a dummy counter to solve the problem. Hopefully this helps, apparently not many people are looking for this.

\newcommand{\mylabel}[1]{
    \ifcsname c@#1\endcsname%
    \else%
        \newcounter{#1}\label{#1}%
    \fi%
}
like image 125
jms Avatar answered Dec 31 '22 14:12

jms