我正在尝试在表格上标记项目。在我的使用中,可能存在多个标签,因此创建标签的初始位置无关紧要(不尝试超链接)。我想使用一个命令来分配标签。所以我认为简单的解决方案是检查引用是否存在,如果不存在,则增加计数器并分配新标签,否则引用它。
我确实注意到,我在交替编译时得到了不同的结果。我还注意到,当ifundefined
单独测试该部分(即打印 true 或 false)时,需要进行两次编译。我相信这是因为 TeX 与其 .aux 文件交互的方式?
\documentclass{article}
\newcounter{myrefcnt}% my referene counter
\makeatletter
\newcommand\myref[1]{% my command
\@ifundefined{r@#1}{%if reference doesnt exist
\refstepcounter{myrefcnt}\themyrefcnt\label{#1}% create a label for reference
}{%
\ref{#1}% else reference it
}%
}
\makeatother
\begin{document}
\textbf{My Attempt:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & \myref{fourlegs}, \myref{lookslikerat} \\
Bat & \myref{lookslikerat} \\
Cheetah & \myref{fourlegs} \\\hline
\end{tabular}
\myref{fourlegs} indicates speciment has four legs.
\myref{lookslikerat} indicates speciment looks like a rat.
\textit{When I run the file, the labels are sometimes 1,2,3,4, but other times 5,6,6,5}
\textbf{I want to produce the following:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & 1, 2 \\
Bat & 2 \\
Cheetah & 1 \\\hline
\end{tabular}
1 indicates speciment has four legs.
2 indicates speciment looks like a rat.
\end{document}
答案1
这样您就可以\label
对在文档开头读取的辅助文件进行前向引用写入,因此所有 r@.. 宏都在第二次运行时定义。您可以创建一个\my@'#1
不记录辅助文件的全局宏,然后以相同的方式在您的宏中测试它。(在这种情况下,您可能\label
根本不需要。
\documentclass{article}
\newcounter{myrefcnt}% my referene counter
\makeatletter
\newcommand\myref[1]{% my command
\@ifundefined{myr@#1}{%if reference doesnt exist
\stepcounter{myrefcnt}\themyrefcnt\expandafter\xdef\csname myr@#1\endcsname{\themyrefcnt}% create a label for reference
}{%
\csname myr@#1\endcsname% else reference it
}%
}
\makeatother
\begin{document}
\textbf{My Attempt:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & \myref{fourlegs}, \myref{lookslikerat} \\
Bat & \myref{lookslikerat} \\
Cheetah & \myref{fourlegs} \\\hline
\end{tabular}
\myref{fourlegs} indicates speciment has four legs.
\myref{lookslikerat} indicates speciment looks like a rat.
\textit{When I run the file, the labels are sometimes 1,2,3,4, but other times 5,6,6,5}
\textbf{I want to produce the following:}
\begin{tabular}{lr}
\hline
Things & Applicable Things \\\hline
Aardvark & 1, 2 \\
Bat & 2 \\
Cheetah & 1 \\\hline
\end{tabular}
1 indicates speciment has four legs.
2 indicates speciment looks like a rat.
\end{document}
您可能仍会遇到对事物进行多次评估的环境问题(例如 amsmath 对齐和 tabularx),因为您需要保护测试,以便试运行不会使每次使用看起来都不是第一次。