我有这个运行良好的命令:
\newcommand{\mytag}[2]{%
\text{#1}%
\@bsphack
\protected@write\@auxout{}%
{\string\newlabel{#2}{{#1}{\thepage}}}%
\@esphack
}
但是当我将包 hyperref 添加为:
\usepackage{hyperref}
\hypersetup{
colorlinks=true, %set true if you want colored links
linktoc=page, %set to all if you want both sections and subsections linked
linkcolor=blue, %choose some color if you want links to stand out
}
然后当我使用我的新命令时 latex 提示我这个错误并且无法编译。错误是:
段落在 \Hy@setref@link 完成之前结束。
我尝试删除所有 .aux 文件,但错误并没有消失。只有当我注释 hyperref 行时,错误才会消失。我该如何解决这个问题?
编辑:
\documentclass{article}
\usepackage [english] {babel}
\usepackage {anysize}
\usepackage [T1]{fontenc}
\usepackage {amsmath, amsthm, amsfonts, amssymb}
\usepackage [utf8]{inputenc}
\usepackage{mathtools}
\usepackage{lipsum}
\usepackage{hyperref} %If you comment this, it works. If you uncomment it doesn't
\makeatletter
%my command
\newcommand{\mytag}[2]{%
\text{#1}%
\@bsphack
\protected@write\@auxout{}%
{\string\newlabel{#2}{{#1}{\thepage}}}%
\@esphack
}
%frougon command. It does not work as expected. It loses the posibility to refer to portions of the equations.
%\newcommand*{\mytag}[2]{\text{#1}\def\@currentlabel{#1}\label{#2}}
\makeatother
\begin{document}
\begin{equation}\label{eq:myeq}
E=\underbrace{\underbrace{mv^2}_{\mytag{kinetic}{eq:myeq_kinetic}}+\underbrace{mgh}_{\mytag{potential}{eq:myeq_potential}}}_{\mytag{total Energy}{eq:myeq_totalE}},
\end{equation}
Eq. \ref{eq:myeq} is the expresion for \ref{eq:myeq_totalE}, which is composed by \ref{eq:myeq_kinetic} and \ref{eq:myeq_potential} energies.
\end{document}
答案1
hyperref
重新定义了一些 LaTeX 命令,包括\label
。事实上,它需要在.aux
文件中存储与每个标签相关的更多数据,以提供其提供的功能。
您的命令后面基本上跟着LaTeX 内核中命令\text{#1}
的定义。因此,它会以与 不兼容的格式将数据写入文件。为了避免此类兼容性问题,最简单的方法是使用来完成精细的工作(根据是否加载 ,这项工作必须有所不同)。由于LaTeX 内核中的 的定义是:\label
.aux
hyperref
\label
hyperref
\label
\def\label#1{\@bsphack
\protected@write\@auxout{}%
{\string\newlabel{#1}{{\@currentlabel}{\thepage}}}%
\@esphack}
并且由于amsmath
也重命名\label
为\ltx@label
,因此您的命令可以翻译如下:
\documentclass{article}
\usepackage{amsmath}
\usepackage{hyperref}
\makeatletter
\newcommand*{\mytag}[2]{\text{#1}\def\@currentlabel{#1}\ltx@label{#2}}
\makeatother
\begin{document}
\begin{equation}\label{eq:myeq}
E = \underbrace{
\underbrace{\frac{1}{2} mv^2}_{\mytag{kinetic}{eq:myeq_kinetic}}
+ \underbrace{mgh}_{\mytag{potential}{eq:myeq_potential}}
}_{\mytag{mechanical energy}{eq:myeq_mechanicalE}}
\end{equation}
Eq.~\ref{eq:myeq} is the expression for~\ref{eq:myeq_mechanicalE}, which is
composed of~\ref{eq:myeq_kinetic} and~\ref{eq:myeq_potential} energies.
\end{document}
注:正如@DavidCarlisle 所说指出,你的\@bsphack
...\@esphack
对在数学模式下毫无用处。