带有节计数器的 tcolorbox 定理的超链接(带 hyperref)不正确

带有节计数器的 tcolorbox 定理的超链接(带 hyperref)不正确

在以下 MWE 中,单击创建的超链接\ref{thm:labelOfTheorem}无法按预期工作:PDF 不会跳转到定理,而是跳转到定义。

\documentclass{book}

\usepackage[most]{tcolorbox}
\newtcbtheorem[number within = section]{theobox}{Theorem}{}{thm}
\newtcbtheorem[use counter from=theobox]{defbox}{Definition}{}{def}
%\newtcbtheorem{defbox}{Definition}{}{def} % A) Use this line instead of the above and the reference works

\usepackage{hyperref} 

\begin{document}
    
\chapter{Chapter}
\section{Section}

\begin{defbox}{}{labelOfDefinition}
    Something defined here
\end{defbox}

\vfill
\section{Another Section} % B) Comment this line out and the reference works

\begin{theobox}{}{labelOfTheorem}
    A Theorem
\end{theobox}

The proof of Theorem~\ref{thm:labelOfTheorem} is left as an exercise to the reader.


\end{document}

超链接的所需行为可以通过两种方式实现(参见 MWE 中的评论):

  • use counter from=theoboxA )不要defbox
  • B) 不要开始新的section

当然,A)和B)都不是解决方案。

很明显,链接因节计数器而中断。如何修复?

答案1

当您使用该部分重置计数器时,表示\the<counter>不再唯一,因此 hyperref 创建了两个具有相同名称的目标。您会在日志中收到一条警告:

destination with the same identifier (name{tcb@[email protected]}) has been 
already used, duplicate ignored

避免这种情况的典型方法是定义计数器表示的 \theH 版本:

\documentclass{book}

\usepackage[most]{tcolorbox}
\newtcbtheorem[number within = section]{theobox}{Theorem}{}{thm}
\newtcbtheorem[use counter from=theobox]{defbox}{Definition}{}{def}
%\newtcbtheorem{defbox}{Definition}{}{def} % A) Use this line instead of the above and the reference works

\usepackage{hyperref}
\makeatletter
\newcommand\theHtcb@cnt@theobox{\thesection.\arabic{tcb@cnt@theobox}}
\makeatother
\begin{document}

\chapter{Chapter}
\section{Section}

\begin{defbox}{}{labelOfDefinition}
    Something defined here
\end{defbox}

\vfill
\section{Another Section} % B) Comment this line out and the reference works

\begin{theobox}{}{labelOfTheorem}
    A Theorem
\end{theobox}

The proof of Theorem~\ref{thm:labelOfTheorem} is left as an exercise to the reader.


\end{document}

相关内容