定义自定义标签

定义自定义标签

是否可以定义一个指令来创建自定义标签,以便以后可以在多个位置引用该标签\ref{...}

例如:

...
\createlabel{l-foo}{22}
...
% later in document:
In line \ref{l-foo} foo-bar. Furthermore, line \ref{l-foo}...
...

应翻译成:

In line 22 foo-bar. Furthermore, line 22...

或者,有没有办法在文档开头的某处定义一组预定义值(不一定是标签机制),以便我以后可以在文本中使用它们。

答案1

您真的需要使用 吗\ref?您可以直接说\newcommand{\foobar}{22},这样输入时\foobar就会得到 22。当然,如果在定义标签之前出现任何引用,这种粗暴的方法就行不通了。要使用\ref,请尝试此方法。

\documentclass{minimal}
\makeatletter
\newcommand{\customlabel}[2]{%
\protected@write \@auxout {}{\string \newlabel {#1}{{#2}{}}}}
\makeatother
\begin{document}
Here is some text. \customlabel{foobar}{22}
Here is some more text \ref{foobar}.
\end{document} 

答案2

我找到了一个适用于 hyperref 的自定义标签解决方案,到处寻找,但总是回到这个页面。(通过谷歌搜索)

Ian 的解决方案(不是与...合作超链接

\makeatletter
\newcommand{\customlabel}[2]{%
\protected@write \@auxout {}{\string \newlabel {#1}{{#2}{}}}}
\makeatother

它不能与 hyperref 一起使用的原因是该包更改了 \newlabel 命令,因此它有 6 个参数。

伊恩答案的修改版本,适用于超链接包裹。

\makeatletter
\newcommand{\customlabel}[2]{%
   \protected@write \@auxout {}{\string \newlabel {#1}{{#2}{\thepage}{#2}{#1}{}} }%
   \hypertarget{#1}{#2}
}
\makeatother

然而这样做意味着修改后的版本需要hyperref 包。

添加 \hypertarget 是为了使使用 \ref 时链接能够正常工作。

答案3

\documentclass{article}

\usepackage{lineno}

\begin{document}

\linenumbers

\modulolinenumbers[255] % To switch off the showing of the numbers on margins

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus
elit, vestibulum ut, placerat ac, adipiscing vitae, felis. Curabitur
dictum gravida mauris. \linelabel{line:Nam}Nam arcu libero,
nonummy eget, consectetuer id, vulputate a, magna. Donec vehicula
augue eu neque. Pellentesque habitant morbi tristique senectus et
netus et malesuada fames ac turpis egestas. Mauris ut leo. Cras
viverra metus rhoncus sem. Nulla et lectus vestibulum urna fringilla
ultrices.  Phasellus eu tellus sit amet tortor gravida placerat.
Integer sapien est, iaculis in, pretium quis, viverra ac, nunc.
Praesent eget sem vel leo ultrices bibendum.  Aenean faucibus.  Morbi
dolor nulla, malesuada eu, pulvinar at, mollis ac, nulla.  Curabitur
auctor semper nulla. Donec varius orci eget risus. Duis nibh mi,
congue eu, accumsan eleifend, sagittis quis, diam. Duis eget orci sit
amet orci dignissim rutrum

The sentence ``Nam arcu libero'' starts at line~\ref{line:Nam}

\end{document}

答案4

那这个呢:

\makeatletter
\newcommand{\mylabel}[2]{%
 \@bsphack\begingroup
 \def\@currentlabel{#2}%
 \label{#1}%
 \endgroup\@esphack
}
\makeatother

另一个示例——为新环境定义自定义标签:

\makeatletter%
\newenvironment{myenvironment}{%
 \addtocounter{mycounter}{1}%
 \def\@currentlabel{{\thesection.\themycounter}}%  custom labelling for this environment
 %%... etc.,  other environment definitions here
}{%
%...
}
\makeatother

相关内容