English 中文(简体)
有办法在LaTeX中检查标签是否已定义吗?
原标题:
  • 时间:2009-01-30 15:10:05
  •  标签:

我在David Hanak的回答之后编辑了这个问题(顺便说一句,谢谢!)。他帮忙语法,但似乎我起初并没有使用正确的函数。

基本上我想让编译器忽略某个标签的多重定义,并且只使用第一个。为了做到这一点,我想要做的就是像这样:

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

然而,这并不起作用,因为总是选择第一选项(无论标签是否被定义)。我认为@ifundefined(以及建议的ifundefined)只适用于命令而不适用于标签,但我不太了解LaTeX。希望有关此事的任何帮助!谢谢!

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.


ewcommand{mylabel}[1]{%
    @ifundefined{c@#1}{%
        
ewcounter{#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.

最佳回答

“@” 是 LaTeX 中的特殊字符。为了使您的声明在语法上正确,您需要添加两行:

makeatletter

ewcommand{mylabel}[1]{
    @ifundefined{#1}{label{#1}}{X}
}
makeatother

第一行将@转换为普通字母,最后一行撤销了它的效果。

更新:您可能还想查看“plain”ifundefined LaTeX宏

更新2

好的,我进行了研究,找出了真正的问题的答案。问题是定义标签并不会创建一个同名的宏,而是在它前面添加了一个"r@"。 所以尝试以下方法:

makeatletter

ewcommand{mylabel}[1]{
    @ifundefined{r@#1}{label{#1}}{X}
}
makeatother

For more technical details, refer to line 3863 of latex.ltx in your LaTeX distribution (where it says def ewlabel{@newl@bel r}).

问题回答

我也不是LaTeX专家,但经过一天的尝试和在互联网上搜索后,以下方法适用于我。我使用了一个虚拟计数器来解决问题。希望这可以帮助到您,显然并不是很多人在寻找这个。


ewcommand{mylabel}[1]{
    ifcsname c@#1endcsname%
    else%
        
ewcounter{#1}label{#1}%
    fi%
}

由Victor Eijkhout编写,《TeX By Topic》,第143页:

defifUnDefinedCs#1{expandafterifxcsname#1endcsname
elax} 

这可以用来检查标签是否被定义;如果没有,则打印标签:


ewcommand{myautoref}[1]{ifUnDefinedCs{r@#1}{color{magenta}IDontKnow{#1}}elseautoref{#1}fi} 




相关问题
热门标签